<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Xylophone]]></title><description><![CDATA[Using everyday analogies and fun illustrations, Xylophone deconstructs scalable software topics, making complex tech concepts easy and enjoyable for any enginee]]></description><link>https://xylophone.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 07 Nov 2026 15:59:11 GMT</lastBuildDate><atom:link href="https://xylophone.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[A Sneak Peek at the View Transition API]]></title><description><![CDATA[Basic understanding of HTML, CSS, and Javascript. Good grasp of the Document Object Model (DOM). An Updated Browser, preferably Chrome. Creating smooth…]]></description><link>https://xylophone.hashnode.dev/a-sneak-peek-at-the-view-transition-api</link><guid isPermaLink="true">https://xylophone.hashnode.dev/a-sneak-peek-at-the-view-transition-api</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[animation]]></category><category><![CDATA[CSS Animation]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Mon, 06 Jan 2025 17:03:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UcBbUBvfrIw/upload/ef68c2f705656ac8df1f723a8e5f3f3d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-pre-requisite">Pre-requisite</h2>
<ul>
<li><p>Basic understanding of HTML, CSS, and Javascript.</p>
</li>
<li><p>Good grasp of the Document Object Model (DOM).</p>
</li>
<li><p>An Updated Browser, preferably Chrome.</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>Creating smooth transitions on the web is a complex task, and calling it challenging is an understatement. After years of fine-tuning to discover the ideal library or tool to alleviate this pain, we can now effortlessly produce straightforward yet stylish animations with just a few lines of code.</p>
<p>At the core of this revolution is the <code>ViewTransitionsAPI</code>, designed to simplify polished transitions by capturing a snapshot of the page. This API allows the Document Object Model (DOM) to seamlessly transition from one state to another by strategically overlapping states.</p>
<p>In this article, you will explore the challenges associated with creating animations on the web. You'll witness firsthand how the <code>ViewTransitionsAPI</code> transforms the process, reducing the complexity to just a few lines of code that you can begin working with immediately.</p>
<p>Additionally, you'll have the opportunity to craft a mock landing page for a blog. By utilizing the <code>ViewTransitionAPI</code>, you will effortlessly incorporate captivating animations into the landing page.</p>
<p>Let's dive right in.</p>
<h2 id="heading-goals">Goals</h2>
<p>After reading this article, you will be able to:</p>
<ul>
<li><p>Gain insight into why the <code>ViewTransitionsAPI</code> is necessary for web development.</p>
</li>
<li><p>Understand the mechanics behind how the <code>ViewTransitionsAPI</code> operates.</p>
</li>
<li><p>Learn how to create straightforward animations using the capabilities of the <code>ViewTransitionsAPI</code>.</p>
</li>
</ul>
<h2 id="heading-the-problem-with-transitions-on-the-web">The Problem With Transitions On the Web</h2>
<p>Although animating individual components on a web page has brought joy, transitioning between web pages and different DOM states on the same page has proven challenging. However, in recent years, the web developer community has witnessed a breakthrough in web animations and page transitions.</p>
<p>In this context, page transitions involve animating the switch between pages and different DOM states within the same page. Unlike mobile applications, where page transitioning is smooth and provides users with contextual navigation cues, the web often replaces the older page instantly without a transition.</p>
<p>The challenge stems from the fact that web transitions require synchronizing parts of the state of the old page with parts of the state of the new page. However, on the web, the old page disappears before the new page arrives, making synchronization impossible.</p>
<p>Unfortunately, animating different DOM states of the same document proves to be very complicated with the current APIs, let alone animating page transitions.</p>
<p>Even something as seemingly simple as a fade becomes challenging when confronted with the task of maintaining the states of both the old and new pages throughout the transition. This difficulty is compounded by current frameworks and the accessibility and usability pitfalls inherent in web development.</p>
<p>Scenarios such as transitioning from a scroll page to a static page or ensuring that states of pages containing videos or iframes don't reset while navigating around the website are commonplace challenges.</p>
<p>To address these issues, one might consider temporarily moving the item to the root of the page, requiring substantial changes to the CSS. While not impossible, it is undeniably difficult.</p>
<p>In contrast, mobile technologies like Android and iOS boast APIs that effortlessly handle such challenges.</p>
<p>To level the playing field, extensive experimentation has led to numerous iterations attempting to solve these problems. A recent and increasingly stable solution gaining popularity is the <code>ViewTransitionAPI</code>, our focal point for today.</p>
<h2 id="heading-view-transitions-api-to-the-rescue">View Transitions API to the rescue!</h2>
<p>The <code>ViewTransitionAPI</code> originated as an idea proposed by the Google web team and is now gaining traction for adoption in various technologies and browsers.</p>
<p>While existing APIs like the <code>CSStransition API</code> and <code>WebAnimationAPI</code> already cater to browser animations, the <code>ViewTransitionAPI</code> stands out as a remarkable addition.</p>
<p>Its uniqueness lies not only in its simplicity but also in its ability to capture two distinct DOM states and seamlessly coordinate their transition—an innovation that sets it apart.</p>
<p>The primary goal of the <code>ViewTransitionAPI</code> is to provide access to both the old and new states before and after a DOM change.</p>
<p>It addresses challenges such as managing the loading and positioning of the old and new content, preventing the old page content from interfering with the new content, and appropriately removing the old content once the transition is successfully achieved.</p>
<h3 id="heading-syntax-and-mechanism">Syntax and Mechanism</h3>
<p>One notable feature of the <code>ViewTransitionAPI</code> lies in the simplicity of its syntax. Achieving easy animations with just a few lines of JavaScript is no small accomplishment.</p>
<p><strong>NOTE:</strong> <em>The snippet below illustrates the fundamental usage of the</em> <code>ViewTransitionAPI</code>. It is presented in pseudocode for explanatory purposes and does not produce any actual results. The syntax would be implemented to demonstrate results in the actual demo.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">spaNavigate</span>(<span class="hljs-params">data</span>) </span>{
  <span class="hljs-comment">// Fallback for browsers that don't support this API:</span>
  <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">document</span>.startViewTransition) {
    updateTheDOM(data);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-comment">// With a transition:</span>
  <span class="hljs-built_in">document</span>.startViewTransition(<span class="hljs-function">() =&gt;</span> updateTheDOM(data));
}
</code></pre>
<ul>
<li><p>The function <code>spaNavigate(data)</code> incorporates an <code>if</code> statement to offer an alternative method of updating the DOM—calling <code>updateTheDOM(data)</code>—in case the browser does not support the <code>ViewTransitionAPI</code>.</p>
</li>
<li><p>Conversely, if the <code>ViewTransitionAPI</code> is supported, the function utilizes a built-in method to update the DOM. This is achieved with the following line: <code>document.startViewTransition(() =&gt; updateTheDOM(data));</code>.</p>
</li>
<li><p>The mechanism behind this is that when the <code>ViewTransitionAPI</code> is invoked using the method <code>document.startViewTransition(() =&gt; updateTheDOM(data));</code>, it captures the current state of the page.</p>
</li>
<li><p>The method <code>updateTheDOM</code> is presented in pseudocode and would be substituted in a real-world context. Whatever replaces it will be the animation used for the transition.</p>
</li>
<li><p>Once the animation is complete, the <code>ViewTransitionAPI</code> updates the DOM by altering the state while retaining the old state. Subsequently, the API captures the new state of the page and executes a transition between both states, avoiding abrupt state changes.</p>
</li>
<li><p>In our upcoming demo, the remarkable aspect to observe is that the <code>ViewTransitionAPI</code> takes care of all the essential tasks—capturing old and new states, managing overlap—using just a few lines of code.</p>
</li>
</ul>
<h3 id="heading-pseudo-classes">Pseudo Classes</h3>
<p>Among the numerous intricacies of the <code>ViewTransitionAPI</code>, a key feature is its provision of pseudo-classes that facilitate the customization of transitions in your CSS file when transitioning from one page to another.</p>
<p>These pseudo-classes group DOM elements in a way that allows the API to manage the transition states. As a result, you can opt to control the animation at various stages of the DOM change, apply distinct animations to different sections of the DOM, or manage the entire page's animation.</p>
<p>While these pseudo-classes serve as entry points for creating custom animations, today's article focuses on understanding how the <code>ViewTransitionAPI</code> operates in the browser through JavaScript.</p>
<p>Nonetheless, having a grasp of these pseudo-classes can be beneficial:</p>
<ul>
<li><p><code>::view-transition</code> : Represents the root of the view transitions overlay, which contains all view transitions and sits above other page content. Used for styling the overall transition container.</p>
</li>
<li><p><code>::view-transition-old</code>: Represents the "old" view state before the transition (a static screenshot). Used to style the old view's appearance during the transition.</p>
</li>
<li><p><code>::view-transition-new</code>: Represents the "new" view state after the transition (a live representation). Used to style the new view's appearance during the transition.</p>
</li>
<li><p><code>::view-transition-image-pair</code>: Represents a pair of old and new views within a transition group. Used to style the visual relationship between the transitioning views.</p>
</li>
</ul>
<h3 id="heading-project-support">Project Support</h3>
<p>On the <a target="_blank" href="https://mdn.github.io/dom-examples/view-transitions/">example provided by the Mozilla Developer Network</a>, a practical demonstration using pure HTML showcases a seamless crossfade transition from one image to another. This feature, being an actual part of HTML, implies that any JavaScript library or framework can integrate it into their technology.</p>
<p>As of now, the stable support for browsers includes this version of the <code>ViewTransitionAPI</code>, offering convenient access to DOM transition changes. Some frameworks have adopted the API using polyfills to create page transitions for Multi-Page Apps (MPAs). Therefore, as of the time of this article's writing, using the <code>ViewTransitionAPI</code> in JavaScript is the most easily accessible browser-stable version.</p>
<p>Several major technologies have embraced and incorporated the <code>ViewTransitionAPI</code> for page transitions, including <code>AstroJS</code>, <code>AngularJS</code>, <code>Svelte</code>/<code>SvelteKit</code>, <code>HTMX</code>, and <code>Nuxt</code>.</p>
<p>It's important to note that any JavaScript script can invoke this API in a supporting browser, but certain frameworks and libraries may provide better support than others.</p>
<h2 id="heading-demo">Demo</h2>
<p>In today's demonstration, we will construct a mock blog landing page featuring several text options. The content will be dynamically sorted by clicking on designated buttons using HTML, CSS, and JavaScript.</p>
<p>Once the project setup is complete, we'll have the capability to easily organize and navigate through the article titles, as demonstrated below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736181814336/984fb654-08e9-45f8-957f-22c595f0d64d.gif" alt class="image--center mx-auto" /></p>
<p>Next, we will leverage the power of the <code>ViewTransitionAPI</code> to introduce basic animations seamlessly during the sorting process. This is a notable enhancement, considering that achieving such animations would typically require an extensive amount of CSS and scripting.</p>
<p>While the demonstration is relatively straightforward, the focus is on showcasing the effectiveness of the <code>ViewTransitionAPI</code> in achieving these animations.</p>
<h3 id="heading-setting-up">Setting Up</h3>
<p>To keep things efficient and dive into the main part swiftly, I'll share the code along with a quick overview of its workings.</p>
<ol>
<li>Create three files.</li>
</ol>
<pre><code class="lang-typescript">viewBlog.html
viewBlog.css
viewBlog.js
</code></pre>
<ul>
<li>As usual, we have three files for the structure of our HTML, CSS for styling and Javascript for some custom behaviour.</li>
</ul>
<ol start="2">
<li>In our HTML file, put the code below:</li>
</ol>
<pre><code class="lang-typescript">&lt;!doctype html&gt;
&lt;html lang=<span class="hljs-string">"en"</span>&gt;
  &lt;head&gt;
    &lt;meta charset=<span class="hljs-string">"UTF-8"</span> /&gt;
    &lt;meta name=<span class="hljs-string">"viewport"</span> content=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;
    &lt;title&gt;View Transitions&lt;/title&gt;
    &lt;link rel=<span class="hljs-string">"stylesheet"</span> href=<span class="hljs-string">"viewBlog.css"</span> /&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"content-grid"</span>&gt;
      &lt;header <span class="hljs-keyword">class</span>=<span class="hljs-string">"primary-header full-width"</span>&gt;
        &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"primary-header__layout breakout-right"</span>&gt;
          &lt;nav <span class="hljs-keyword">class</span>=<span class="hljs-string">"primary-navigation"</span>&gt;
            &lt;ul&gt;
              &lt;li&gt;&lt;a href=<span class="hljs-string">"#"</span>&gt;About Open Replay&lt;<span class="hljs-regexp">/a&gt;&lt;/</span>li&gt;
              &lt;li&gt;&lt;a href=<span class="hljs-string">"#"</span>&gt;Tutorials&lt;<span class="hljs-regexp">/a&gt;&lt;/</span>li&gt;
              &lt;li&gt;&lt;a href=<span class="hljs-string">"#"</span>&gt;Product&lt;<span class="hljs-regexp">/a&gt;&lt;/</span>li&gt;
              &lt;li&gt;&lt;a aria-current=<span class="hljs-string">"page"</span> href=<span class="hljs-string">"#"</span>&gt;Write <span class="hljs-keyword">for</span> us&lt;<span class="hljs-regexp">/a&gt;&lt;/</span>li&gt;
            &lt;/ul&gt;
          &lt;/nav&gt;

          &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"account-links"</span>&gt;
            &lt;a href=<span class="hljs-string">"#"</span>&gt;Log In&lt;/a&gt;
            &lt;a href=<span class="hljs-string">"#"</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"create-account"</span>&gt;Get Started&lt;/a&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/header&gt;
      &lt;nav aria-label=<span class="hljs-string">"Breadcrumb"</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"breadcrumbs"</span>&gt;
        &lt;ol&gt;
          &lt;li&gt;&lt;a href=<span class="hljs-string">"#"</span>&gt;Product&lt;<span class="hljs-regexp">/a&gt;&lt;/</span>li&gt;
          &lt;li&gt;&lt;a href=<span class="hljs-string">"#"</span> aria-current=<span class="hljs-string">"page"</span>&gt;Blog&lt;<span class="hljs-regexp">/a&gt;&lt;/</span>li&gt;
        &lt;/ol&gt;
      &lt;/nav&gt;
      &lt;main <span class="hljs-keyword">class</span>=<span class="hljs-string">"main-with-aside"</span>&gt;
        &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"flow"</span>&gt;
          &lt;h1&gt;Our most read articles&lt;/h1&gt;
          &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"filter"</span>&gt;
            &lt;h2 <span class="hljs-keyword">class</span>=<span class="hljs-string">"visually-hidden"</span>&gt;Filter by <span class="hljs-keyword">type</span> <span class="hljs-keyword">of</span> article&lt;/h2&gt;
            &lt;button <span class="hljs-keyword">class</span>=<span class="hljs-string">"filter-btn active"</span> data-filter=<span class="hljs-string">"all"</span>&gt;All&lt;/button&gt;
            &lt;button <span class="hljs-keyword">class</span>=<span class="hljs-string">"filter-btn"</span> data-filter=<span class="hljs-string">"frontend"</span>&gt;Frontend&lt;/button&gt;
            &lt;button <span class="hljs-keyword">class</span>=<span class="hljs-string">"filter-btn"</span> data-filter=<span class="hljs-string">"backend"</span>&gt;Backend&lt;/button&gt;
            &lt;button <span class="hljs-keyword">class</span>=<span class="hljs-string">"filter-btn"</span> data-filter=<span class="hljs-string">"fullstack"</span>&gt;
              Fullstack
            &lt;/button&gt;
          &lt;/div&gt;

          &lt;ul <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-list"</span>&gt;
            &lt;li <span class="hljs-keyword">class</span>=<span class="hljs-string">"article"</span> data-category=<span class="hljs-string">"fullstack"</span>&gt;
              &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-details"</span>&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-date"</span>&gt;Published on : Jan <span class="hljs-number">29</span>th <span class="hljs-number">2023</span>&lt;/span&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-category"</span>&gt;Fullstack&lt;/span&gt;
              &lt;/div&gt;
              &lt;h2 <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-name"</span>&gt;Building a blog <span class="hljs-keyword">with</span> Next JS&lt;/h2&gt;
            &lt;/li&gt;

            &lt;li <span class="hljs-keyword">class</span>=<span class="hljs-string">"article"</span> data-category=<span class="hljs-string">"fullstack"</span>&gt;
              &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-details"</span>&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-date"</span>&gt;Published on : March <span class="hljs-number">1</span>st <span class="hljs-number">2023</span>&lt;/span&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-category"</span>&gt;Fullstack&lt;/span&gt;
              &lt;/div&gt;
              &lt;h2 <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-name"</span>&gt;
                Setting up React <span class="hljs-keyword">with</span> a Vector Database
              &lt;/h2&gt;
            &lt;/li&gt;

            &lt;li <span class="hljs-keyword">class</span>=<span class="hljs-string">"article"</span> data-category=<span class="hljs-string">"backend"</span>&gt;
              &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-details"</span>&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-date"</span>
                  &gt;Published on : August <span class="hljs-number">23</span>rd <span class="hljs-number">2023</span>&lt;/span
                &gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-category"</span>&gt;Backend&lt;/span&gt;
              &lt;/div&gt;
              &lt;h2 <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-name"</span>&gt;NodeJS Security Best Practices&lt;/h2&gt;
            &lt;/li&gt;

            &lt;li <span class="hljs-keyword">class</span>=<span class="hljs-string">"article"</span> data-category=<span class="hljs-string">"frontend"</span>&gt;
              &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-details"</span>&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-date"</span>&gt;Published on : June <span class="hljs-number">7</span>th <span class="hljs-number">2023</span>&lt;/span&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-category"</span>&gt;Frontend&lt;/span&gt;
              &lt;/div&gt;
              &lt;h2 <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-name"</span>&gt;CSS trigonometry&lt;/h2&gt;
            &lt;/li&gt;

            &lt;li <span class="hljs-keyword">class</span>=<span class="hljs-string">"article"</span> data-category=<span class="hljs-string">"frontend"</span>&gt;
              &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-details"</span>&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-date"</span>&gt;Published on : September <span class="hljs-number">14</span>th&lt;/span&gt;
                &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-category"</span>&gt;Frontend&lt;/span&gt;
              &lt;/div&gt;
              &lt;h2 <span class="hljs-keyword">class</span>=<span class="hljs-string">"article-name"</span>&gt;View Transitions API&lt;/h2&gt;
            &lt;/li&gt;
          &lt;/ul&gt;
        &lt;/div&gt;
      &lt;/main&gt;
    &lt;/div&gt;
    &lt;script src=<span class="hljs-string">"viewBlog.js"</span>&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<ul>
<li><p>This code comprises markup for our simulated webpage, linked to both our CSS and JavaScript files, which will be addressed shortly.</p>
</li>
<li><p>It's essential to observe that for sorting the text content, JavaScript will be employed. Consequently, the HTML structure incorporates <code>data-</code> attributes such as <code>data-filter</code> and <code>data-category</code> to facilitate straightforward sorting with JavaScript.</p>
</li>
<li><p>Here's a glimpse of the raw structure of the page:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736181863365/9bc5006e-df4c-4e64-8c10-75861b241199.gif" alt class="image--center mx-auto" /></p>
<ol start="3">
<li>On to <code>viewBlog.css</code> for styling.</li>
</ol>
<pre><code class="lang-css">*,
*<span class="hljs-selector-pseudo">::before</span>,
*<span class="hljs-selector-pseudo">::after</span> {
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: system-ui, sans-serif;
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">1.7</span>;
}

<span class="hljs-selector-class">.visually-hidden</span> {
  <span class="hljs-attribute">clip</span>: <span class="hljs-built_in">rect</span>(<span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span>);
  <span class="hljs-attribute">clip-path</span>: <span class="hljs-built_in">inset</span>(<span class="hljs-number">50%</span>);
  <span class="hljs-attribute">height</span>: <span class="hljs-number">1px</span>;
  <span class="hljs-attribute">overflow</span>: hidden;
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">white-space</span>: nowrap;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">1px</span>;
}

<span class="hljs-selector-class">.flow</span> &gt; * + * {
  <span class="hljs-attribute">margin-block-start</span>: <span class="hljs-built_in">var</span>(--flow-spacing, <span class="hljs-number">1rem</span>);
}

<span class="hljs-selector-class">.content-grid</span> {
  <span class="hljs-attribute">--container-max-width</span>: <span class="hljs-number">60rem</span>;
  <span class="hljs-attribute">--min-inline-margin</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>:
    [full-width-start breakout-left-start] <span class="hljs-built_in">minmax</span>(<span class="hljs-number">1rem</span>, <span class="hljs-number">1</span>fr)
    [content-start breakout-right-start] <span class="hljs-built_in">min</span>(
      <span class="hljs-number">100%</span> - var(--min-inline-margin),
      <span class="hljs-built_in">var</span>(--container-max-width)
    )
    [content-end breakout-left-start] <span class="hljs-built_in">minmax</span>(<span class="hljs-number">1rem</span>, <span class="hljs-number">1</span>fr)
    [full-width-end breakout-right-end];
}

<span class="hljs-selector-class">.content-grid</span> &gt; *,
<span class="hljs-selector-class">.full-width</span> &gt; * {
  <span class="hljs-attribute">grid-column</span>: content;
}

<span class="hljs-selector-class">.content-grid</span> &gt; <span class="hljs-selector-class">.full-width</span> {
  <span class="hljs-attribute">grid-column</span>: full-width;

  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: inherit;
}

<span class="hljs-selector-class">.breakout-right</span> {
  <span class="hljs-attribute">grid-column</span>: breakout-right;
}

<span class="hljs-selector-class">.breakout-left</span> {
  <span class="hljs-attribute">grid-column</span>: breakout-left;
}

<span class="hljs-selector-class">.primary-header</span> {
  <span class="hljs-attribute">margin-block-end</span>: <span class="hljs-number">3rem</span>;
  <span class="hljs-attribute">border-block-end</span>: <span class="hljs-number">1px</span> solid <span class="hljs-built_in">var</span>(--separator-color, black);
}

<span class="hljs-selector-class">.primary-header__layout</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">justify-content</span>: space-between;

  <span class="hljs-comment">/*   grid-column: content-start / full-width-end; */</span>
}

<span class="hljs-selector-class">.primary-navigation</span> &gt; <span class="hljs-selector-tag">ul</span> {
  <span class="hljs-attribute">list-style</span>: none;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-built_in">var</span>(--navigation-padding, <span class="hljs-number">1rem</span>) <span class="hljs-number">0</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">gap</span>: <span class="hljs-built_in">clamp</span>(<span class="hljs-number">1rem</span>, <span class="hljs-number">5</span>vi, <span class="hljs-number">2.5rem</span>);
}

<span class="hljs-selector-pseudo">:is(.primary-navigation</span>, <span class="hljs-selector-class">.account-links</span>) <span class="hljs-selector-pseudo">:where(a)</span> {
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">500</span>;
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--link-color, #<span class="hljs-number">777</span>);
}

<span class="hljs-selector-pseudo">:is(.primary-navigation</span>, <span class="hljs-selector-class">.account-links</span>)
  <span class="hljs-selector-pseudo">:where(a</span><span class="hljs-selector-pseudo">:hover</span>, <span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:focus</span>, <span class="hljs-selector-tag">a</span><span class="hljs-selector-attr">[aria-current=<span class="hljs-string">"page"</span>]</span>) {
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--link-current-color, #<span class="hljs-number">111</span>);
}

<span class="hljs-selector-class">.account-links</span> {
  <span class="hljs-attribute">display</span>: flex;
}

<span class="hljs-selector-class">.account-links</span> &gt; * {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">padding-block</span>: <span class="hljs-built_in">var</span>(--navigation-padding, <span class="hljs-number">1rem</span>);
  <span class="hljs-attribute">padding-inline</span>: <span class="hljs-number">3rem</span>;
}

<span class="hljs-selector-class">.create-account</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">var</span>(--button-bg, #<span class="hljs-number">333</span>);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--button-text, white);
}

<span class="hljs-selector-class">.main-with-aside</span> {
  <span class="hljs-attribute">--flow-spacing</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">3rem</span>;
}

<span class="hljs-selector-class">.main-with-aside</span> &gt; <span class="hljs-selector-pseudo">:not(aside)</span> {
  <span class="hljs-attribute">flex-basis</span>: <span class="hljs-number">55ch</span>;
  <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">999</span>;
}

<span class="hljs-selector-class">.main-with-aside</span> &gt; <span class="hljs-selector-tag">aside</span> {
  <span class="hljs-attribute">flex-basis</span>: <span class="hljs-number">325px</span>;
  <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">1</span>;
}

<span class="hljs-selector-class">.breadcrumbs</span> <span class="hljs-selector-tag">ol</span> {
  <span class="hljs-attribute">list-style</span>: none;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">0.5rem</span>;
}

<span class="hljs-selector-class">.breadcrumbs</span> <span class="hljs-selector-tag">a</span> {
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.25rem</span> <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">100vw</span>;
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">var</span>(--breadcrumb-color, #eee);
  <span class="hljs-attribute">color</span>: inherit;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">500</span>;
  <span class="hljs-attribute">text-decoration</span>: none;
}

<span class="hljs-selector-class">.breadcrumbs</span> <span class="hljs-selector-tag">li</span><span class="hljs-selector-pseudo">:not(</span><span class="hljs-selector-pseudo">:last-child)</span><span class="hljs-selector-pseudo">::after</span> {
  <span class="hljs-attribute">content</span>: <span class="hljs-string">" / "</span>;
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.75em</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">100</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">skew</span>(-<span class="hljs-number">20deg</span>);
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">margin-inline</span>: <span class="hljs-number">0.5em</span> <span class="hljs-number">0</span>;
}

<span class="hljs-selector-class">.breadcrumbs</span> <span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:hover</span>,
<span class="hljs-selector-class">.breadcrumbs</span> <span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:focus</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#ccc</span>;
}

<span class="hljs-selector-class">.article-list</span> {
  <span class="hljs-comment">/* display: grid; */</span>
  <span class="hljs-attribute">list-style</span>: none;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
}

<span class="hljs-selector-class">.article</span><span class="hljs-selector-pseudo">:not(</span><span class="hljs-selector-pseudo">:last-child)</span><span class="hljs-selector-pseudo">:not(</span><span class="hljs-selector-pseudo">:has(+</span> <span class="hljs-selector-attr">[hidden]</span>)) {
  <span class="hljs-attribute">padding-bottom</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">border-bottom</span>: <span class="hljs-number">1px</span> solid black;
}

<span class="hljs-selector-class">.article-date</span><span class="hljs-selector-pseudo">::after</span> {
  <span class="hljs-attribute">content</span>: <span class="hljs-string">" •"</span>;
}

<span class="hljs-selector-class">.filter</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">0.5rem</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
}

<span class="hljs-selector-class">.filter-btn</span> {
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">text-transform</span>: uppercase;
  <span class="hljs-attribute">background</span>: transparent;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">0.25rem</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.25rem</span> <span class="hljs-number">1rem</span>;
}

<span class="hljs-selector-class">.filter-btn</span><span class="hljs-selector-pseudo">:hover</span>,
<span class="hljs-selector-class">.filter-btn</span><span class="hljs-selector-pseudo">:focus</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#ccc</span>;
}

<span class="hljs-selector-class">.filter-btn</span><span class="hljs-selector-class">.active</span> {
  <span class="hljs-attribute">background</span>: black;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0.5rem</span> <span class="hljs-built_in">rgb</span>(<span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> / <span class="hljs-number">0.2</span>);
}
</code></pre>
<ul>
<li><p>This gives us a visually appealing page with distinct headings and navigation buttons, although currently non-functional.</p>
</li>
<li><p>At this point, the navigation buttons remain inactive, providing us with a static page illustrated below:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736181986121/c9d16d5a-7f6e-4975-8114-41253f559e52.gif" alt class="image--center mx-auto" /></p>
<ol start="3">
<li>Next up, our aim is to develop a script enabling seamless navigation between various article categories. Upon clicking on a navigation bar option such as "All," "Fullstack," and others, the script will dynamically update the display to show only articles associated with the selected tag.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> filterList = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".filter"</span>);
<span class="hljs-keyword">const</span> filterButtons = filterList.querySelectorAll(<span class="hljs-string">".filter-btn"</span>);
<span class="hljs-keyword">const</span> articles = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">".article"</span>);

filterButtons.forEach(<span class="hljs-function">(<span class="hljs-params">button</span>) =&gt;</span> {
  button.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> filter = e.target.getAttribute(<span class="hljs-string">"data-filter"</span>);
    updateActiveButton(e.target);
    filterArticles(filter);
  });
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateActiveButton</span>(<span class="hljs-params">newButton</span>) </span>{
  filterList.querySelector(<span class="hljs-string">".active"</span>).classList.remove(<span class="hljs-string">"active"</span>);
  newButton.classList.add(<span class="hljs-string">"active"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">filterArticles</span>(<span class="hljs-params">articleFilter</span>) </span>{
  articles.forEach(<span class="hljs-function">(<span class="hljs-params">article</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> articleCategory = article.getAttribute(<span class="hljs-string">"data-category"</span>);
    <span class="hljs-keyword">if</span> (articleFilter === <span class="hljs-string">"all"</span> || articleFilter === articleCategory) {
      article.removeAttribute(<span class="hljs-string">"hidden"</span>);
    } <span class="hljs-keyword">else</span> {
      article.setAttribute(<span class="hljs-string">"hidden"</span>, <span class="hljs-string">""</span>);
    }
  });
}
</code></pre>
<ul>
<li><p>First, we begin by selecting DOM elements using their respective class names.</p>
</li>
<li><p>When a filter button is clicked, the filter category is extracted from the button's <code>data-filter</code> attribute. Subsequently, two functions are invoked: <code>updateActiveButton</code> visually highlights the active button, while <code>filterArticles</code> filters articles based on the selected category.</p>
</li>
<li><p>The <code>updateActiveButton</code> function accepts a button as a parameter. It identifies the currently active button and modifies its visual state by adding or removing the <code>active</code> class.</p>
</li>
<li><p>Meanwhile, the <code>filterArticles</code> function takes a filter category as a parameter. It iterates through the articles, showing or hiding them based on whether they match the selected category. If the category is "all," it displays all articles.</p>
</li>
<li><p>It's worth noting that the process allows for seamless switching based on the clicked option. This transition occurs instantly, altering the DOM contents without any animations.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736182053999/6e83f3df-dac4-40c0-b280-52cec4dff4a9.gif" alt class="image--center mx-auto" /></p>
<h3 id="heading-applying-animations">Applying Animations</h3>
<p>Our aim now is to infuse a modern touch into the webpage and provide users with a more dynamic experience. Thanks to the <code>ViewTransitionsAPI</code>, achieving this is a breeze. Take note of how I leverage it to introduce animations.</p>
<ol>
<li>Begin by instructing the browser to animate transitions when switching between options. This means that when articles are rendered based on filters, a smooth animation will accompany the transition. Implement the following change within the <code>filterButtons</code> loop to enable this animation:</li>
</ol>
<pre><code class="lang-javascript">filterButtons.forEach(<span class="hljs-function">(<span class="hljs-params">button</span>) =&gt;</span> {
  button.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> filter = e.target.getAttribute(<span class="hljs-string">"data-filter"</span>);
    <span class="hljs-comment">// New Function</span>
    <span class="hljs-built_in">document</span>.startViewTransition(<span class="hljs-function">() =&gt;</span> {
      updateActiveButton(e.target);
      filterArticles(filter);
    });
  });
});
</code></pre>
<ul>
<li><p>To facilitate the animation of the transition, I introduced a new method provided by the <code>ViewTransitionsAPI</code> called <code>document.startViewTransition</code>.</p>
</li>
<li><p>Subsequently, I encapsulated the filtering functions within the <code>document.startViewTransition</code>. This ensures that whenever the page initiates a filter, it undergoes an animated transition first. Isn't it exhilarating?</p>
</li>
<li><p>Take a moment to observe the image below. It vividly illustrates how the transition unfolds when filtering articles—gradually animated through cross-fading, the primary animation feature offered by the <code>ViewTransitionsAPI</code>:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736182472261/81562a94-6a2a-47b7-9c8a-6028059a49f4.gif" alt class="image--center mx-auto" /></p>
<ol start="2">
<li>Nonetheless, it's essential to acknowledge that the <code>ViewTransitionsAPI</code> might not be universally supported across all browsers. Hence, a fallback mechanism is necessary. In our <code>filterButtons</code> loop, we will incorporate a fallback solution to ensure that if the API is not supported, the elements will undergo an instant change without any animation.</li>
</ol>
<pre><code class="lang-javascript">filterButtons.forEach(<span class="hljs-function">(<span class="hljs-params">button</span>) =&gt;</span> {
  button.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> filter = e.target.getAttribute(<span class="hljs-string">"data-filter"</span>);
    <span class="hljs-comment">// New IF statement</span>
    <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">document</span>.startViewTransition) {
      updateActiveButton(e.target);
      filterArticles(filter);
    }
    <span class="hljs-built_in">document</span>.startViewTransition(<span class="hljs-function">() =&gt;</span> {
      updateActiveButton(e.target);
      filterArticles(filter);
    });
  });
});
</code></pre>
<ul>
<li>With our added fallback, <code>if (!document.startViewTransition)</code>, the browser handles scenarios where the <code>ViewTransitionsAPI</code> is not supported. In such cases, the filtering through articles proceeds without animation, ensuring a seamless experience even in the absence of API support.</li>
</ul>
<p>As mentioned earlier, the <code>ViewTransitionsAPI</code> comes with pseudo-classes that facilitate the animation of DOM states at various stages, enabling the animation of the entire webpage or specific sections of the DOM.</p>
<p>Suppose we wish to style the lines and elements separating the articles on the demo page. This can be achieved using either Javascript or CSS by assigning a view transition name to the relevant elements.</p>
<p>Opting for Javascript is particularly advantageous because it allows us to dynamically generate unique view transition names for each element we intend to animate. This approach simplifies the process of creating and applying view transitions to animate these elements effectively.</p>
<ol start="3">
<li>To do animate specific elements, make these changes to <code>viewBlog.js</code>.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> filterList = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".filter"</span>);
<span class="hljs-keyword">const</span> filterButtons = filterList.querySelectorAll(<span class="hljs-string">".filter-btn"</span>);
<span class="hljs-keyword">const</span> articles = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">".article"</span>);

<span class="hljs-keyword">let</span> articleIndex = <span class="hljs-number">0</span>; <span class="hljs-comment">// New Line</span>

<span class="hljs-comment">// New Loop</span>
articles.forEach(<span class="hljs-function">(<span class="hljs-params">article</span>) =&gt;</span> {
  article.style.viewTransitionName = <span class="hljs-string">`title-<span class="hljs-subst">${++articleIndex}</span>`</span>;
});
</code></pre>
<ul>
<li><p>After the part of your code where you make DOM declarations, add the next two pieces of code.</p>
</li>
<li><p>What those two lines, specifically the new loop, <code>articles.forEach</code>, do is to create a view transition name for every DOM element with the class <code>article</code>. Then, instead of only cross-fading the entire page, it will also cross-fade the specific elements.</p>
</li>
<li><p>The idea here is that to create a basic animation for specific elements, all you have to do is give them a view transition name. Now, isn't that wonderful?</p>
</li>
<li><p>In the image below, notice how the break lines and article titles are sliding up and down when you change the filter option:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736182228015/1d9b251c-7d6b-45f3-a30b-56e43a12f017.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-browser-support">Browser Support</h2>
<p><code>The ViewTransitionsAPI</code> is currently shipped in two modes. The first is the JavaScript API, which can be used directly or integrated into various frameworks. The second mode allows for direct use in HTML, though it is considered crude and isn't publicly available at the time of writing this article.</p>
<p>Major browsers that currently support the direct use of <code>ViewTransitionsAPI</code> include Chrome, Edge, and Opera.</p>
<p>It's important to note that many features of this API are still experimental. Therefore, I strongly recommend reviewing the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition">browser support documentation</a> before implementation.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article is just a beginning in exploring a vast field, akin to taking a stab at a tree trunk. Trust me, this tree holds all the nectar you need for web animations, but it will take time to fully appreciate its richness.</p>
<p>As of the time of writing this piece, some features are still primarily experimental, with support limited to a few browsers at most.</p>
<p>However, don't let this discourage you from experimenting with what promises to be a significant advancement in the web animations landscape. Exploring the <code>ViewTransitionsAPI</code> might take some time before a deep dive is possible, but with this article, you've gained a substantial understanding of what it is and how it can be applied.</p>
<p>Continue to explore and stay tuned to this blog for more comprehensive updates on this topic. Until then, to all my animated enthusiasts, cheers!</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition">MDN Documentation on View Transitions API</a></p>
</li>
<li><p><a target="_blank" href="https://developer.chrome.com/docs/web-platform/view-transitions">Google article on web transitions</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[CSS Cascading Layers]]></title><description><![CDATA[A Practical Walkthrough]]></description><link>https://xylophone.hashnode.dev/css-cascading-layers</link><guid isPermaLink="true">https://xylophone.hashnode.dev/css-cascading-layers</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[CSS3]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Mon, 06 Jan 2025 16:34:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/SpCrTUG2nu8/upload/b06027c8cafe59434fb68b5981ce8661.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-pre-requisite">Pre-requisite</h2>
<p>To maximize the benefits of this article, ensure you meet the following requirements:</p>
<ul>
<li><p>Possess a strong grasp of HTML and CSS.</p>
</li>
<li><p>Demonstrate an understanding of how the CSS cascade operates.</p>
</li>
<li><p>Have knowledge of CSS specificity.</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>The cascade and specificity stand as fundamental technologies that both contribute to the allure and occasional challenges of working with CSS.</p>
<p>Fear not, fellow web enthusiasts, for a solution is on the horizon. The CSS cascade layers are here to alleviate most of your woes when dealing with CSS, particularly when you need to override styles for custom CSS utility classes, navigate through frameworks, or simplify long and complex selectors.</p>
<p>In this article, not only will you have the opportunity to practice utilizing cascading layers through various instances and demonstrations, but you will also comprehend the advanced implementation of layering within the browser. Additionally, you'll gain insight into the impact of frameworks on cascading layers and learn how to leverage developer tools to identify preferred styles and layers.</p>
<h2 id="heading-goals">Goals</h2>
<p>If you find yourself exhausted from the struggle of identifying CSS selectors causing specificity bugs, have a penchant for code organization, or simply revel in front-end development, then the next few minutes spent on this article are bound to be delightful.</p>
<p>By the end of this read, you will acquire the following insights:</p>
<ul>
<li><p>Grasp the importance of better control over CSS specificity.</p>
</li>
<li><p>Understand how layering works in CSS.</p>
</li>
<li><p>Recognize how cascading layers provide enhanced control over specificity.</p>
</li>
<li><p>Learn effective techniques for organizing your CSS code using cascading layers.</p>
</li>
<li><p>Acquire skills in utilizing various tweaks when dealing with multiple cascading layers.</p>
</li>
</ul>
<h2 id="heading-specificity-issues">Specificity Issues</h2>
<p>One of the most common challenges in CSS is dealing with specificity issues, often leading to the creation of overly complex selectors. This complexity arises when attempting to override styles on the fly, sometimes even resorting to the use of the <code>!important</code> marker, a practice notorious for triggering unnecessary debugging sessions.</p>
<p>Specificity issues manifest when a selector or a set of selectors override another, leaving us puzzled as to why this preference occurs or why one selector takes precedence over another.</p>
<p>Enter cascading layers, a solution that empowers us to dictate which selectors take precedence and allows us to arrange the order of preference for applying a group of selectors.</p>
<p>Before delving into cascading layers, it's crucial to understand why certain selectors are favored over others.</p>
<h2 id="heading-cascade-layer-principles">Cascade Layer Principles</h2>
<p>Up until now, the concept of working with layers may not have been at the forefront of our concerns.</p>
<p>As we employ CSS to style HTML elements, the stylesheets are organized into layers, specifically the author layer, the user layer, and the user agent stylesheet layer.</p>
<p>Have you ever inspected elements in your developer tools and noticed the options displayed next to the CSS styling? Yes, those are your layers, as illustrated in the image below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736180733482/e382ed4f-811b-4311-b42f-e8c934624878.gif" alt class="image--center mx-auto" /></p>
<p>In the image above, note the cursor highlighting the "cascade.css," representing the author layer, and the "user agent stylesheet," representing the user agent stylesheet layer.</p>
<p>The author layer encompasses the stylesheet generated by the developer's code, essentially our CSS file.</p>
<p>Conversely, the user agent stylesheet layer comprises the default styling embedded within browsers. This explains why browsers may exhibit variations in rendering certain HTML elements by default.</p>
<p>As for the user layer, it falls between the user agent stylesheet and the author layer, housing styles specified by the user—often through browser extensions or settings. While relevant, it's not a focal point for our discussion today.</p>
<p>Despite being a fundamental mechanism in how CSS operates, the user agent stylesheet layer hasn't been a significant concern because the author layer consistently takes precedence. It doesn't matter if the user agent layer has a conflicting selector with higher specificity; the author layer will always override it. In comparing styles across different layers, the pivotal criterion for preference is the importance of the layer.</p>
<p>The innovation introduced by the new cascading layer API empowers us to establish and determine the order of preference for various layers within the author layer. These layers enable us to organize our CSS code effectively, rendering the specificity of selectors less crucial compared to the strategic arrangement of layers in the CSS code.</p>
<h3 id="heading-what-are-cascade-layers">What are Cascade Layers?</h3>
<p>Cascade layers represent a recently established and widely adopted stable CSS API, offering developers the capability to craft specificity-based layers and enhance the organization of CSS architecture.</p>
<p>This marks a significant advancement that was not achievable in the past, where reliance on selector specificity or the <code>!important</code> rule was necessary to achieve desired effects.</p>
<p>While there are some scoping considerations to bear in mind when employing cascading layers, they nonetheless provide substantial assistance in addressing specificity concerns.</p>
<p>To create layers, utilize the <code>@layer</code> keyword followed by the name of the layer, encapsulating the styles within it. The syntax is illustrated below:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@layer</span> newlayer {
  <span class="hljs-comment">/* Some CSS styling */</span>
}
</code></pre>
<ul>
<li>The provided syntax illustrates how to create layers, and rest assured, there are numerous code examples in this article to vividly demonstrate the impact of layers.</li>
</ul>
<p>An evident advantage offered by layering is the enhanced architectural control over our styles. This proves especially valuable when dealing with third-party frameworks or extensive CSS codebases, as it allows us to assert direct control over the ordering of our styling.</p>
<p>Now, let's witness this in action.</p>
<h2 id="heading-creating-a-single-layer">Creating a Single Layer</h2>
<p>Layering, or the use of cascade layers as I prefer to call it, enables the incorporation of one or multiple layers within a single CSS file.</p>
<p>In this section of the article, we'll examine a navigation bar and a hero section. Subsequently, we'll encounter a specificity issue that we can resolve by creating a single cascade layer.</p>
<pre><code class="lang-typescript">&lt;!-- Navigation Bar --&gt;
&lt;nav <span class="hljs-keyword">class</span>=<span class="hljs-string">"nav-list"</span>&gt;
  &lt;a href=<span class="hljs-string">"#"</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"button"</span>&gt;Home&lt;/a&gt;
  &lt;a href=<span class="hljs-string">"#"</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"button"</span>&gt;About&lt;/a&gt;
  &lt;a href=<span class="hljs-string">"#"</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"button"</span>&gt;Services&lt;/a&gt;
  &lt;a href=<span class="hljs-string">"#"</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"button"</span>&gt;Contact&lt;/a&gt;
&lt;/nav&gt;

&lt;!-- Hero Section --&gt;
&lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"hero-section"</span>&gt;
  &lt;h1&gt;Welcome to Your Website&lt;/h1&gt;
  &lt;p&gt;This is a simple and elegant website template.&lt;/p&gt;
  &lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"button"</span>&gt;Learn More&lt;/div&gt;
&lt;/div&gt;
</code></pre>
<ul>
<li><p>The key observation from the provided HTML code is the arrangement and combination of selectors.</p>
</li>
<li><p>Within the <code>nav</code> element, there are <code>a</code> elements that include a <code>button</code> class.</p>
</li>
<li><p>Similarly, in the hero section, there are <code>div</code> elements that also contain a <code>button</code> class.</p>
</li>
<li><p>Consequently, our expectation is that everything with the <code>button</code> class should have the same styling.</p>
</li>
</ul>
<p>To apply styles to the HTML using CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
}

<span class="hljs-comment">/* Navigation Bar */</span>
<span class="hljs-selector-tag">nav</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-class">.nav-list</span> <span class="hljs-selector-tag">a</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
}

<span class="hljs-comment">/* Hero Section */</span>
<span class="hljs-selector-class">.hero-section</span> {
  <span class="hljs-attribute">background-size</span>: cover;
  <span class="hljs-attribute">background-position</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#4caf50</span>;
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">100px</span> <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">48px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">40px</span>;
}

<span class="hljs-selector-class">.button</span> {
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4caf50</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}
</code></pre>
<ul>
<li><p>Observe that the <code>.nav-list a</code> and <code>.button</code> selectors exhibit a conflict in the property and value for <code>background-color</code>. Initially, one might expect the <code>.button</code> class to be uniformly applied to all elements sharing that class.</p>
</li>
<li><p>However, contrary to this expectation, the <code>background-color</code> value of <code>.nav-list a</code> takes precedence. This implies a specificity issue, where the most specific selector is favored instead of the one declared later.</p>
</li>
<li><p>As depicted in the image below, note how the buttons in the navigation bar appear white, while the button in the hero section deviates from this styling:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736180824112/d5ddac78-9c8d-4bd6-bb86-93ca7d2e1920.gif" alt class="image--center mx-auto" /></p>
<p>With the application of cascade layers, we can resolve this problem with little effort by specifying the preferred layer. To achieve this, we employ the <code>@layer</code> keyword to create a layer for the desired CSS. Here are the modifications we would make to create a layer for the CSS above:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
}

<span class="hljs-keyword">@layer</span> navigation {
  <span class="hljs-comment">/* Navigation Bar */</span>
  <span class="hljs-selector-tag">nav</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">text-align</span>: center;
  }

  <span class="hljs-selector-class">.nav-list</span> <span class="hljs-selector-tag">a</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> <span class="hljs-number">15px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  }
}

<span class="hljs-comment">/* Hero Section */</span>
<span class="hljs-selector-class">.hero-section</span> {
  <span class="hljs-attribute">background-size</span>: cover;
  <span class="hljs-attribute">background-position</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#4caf50</span>;
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">100px</span> <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">48px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">40px</span>;
}

<span class="hljs-selector-class">.button</span> {
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4caf50</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}
</code></pre>
<ul>
<li><p>In the provided code, a CSS layer was created using the <code>@layer</code> keyword, encapsulating all navigation-related CSS within <code>@layer navigation{}</code>.</p>
</li>
<li><p>This swift action resolves our specificity issue. As evident in the image below, observe that all buttons in the navigation are now consistently styled in the same manner as the other button with the <code>.button</code> class:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736180860282/5fb5ec2d-de7d-41fe-b905-a721a09667d5.gif" alt class="image--center mx-auto" /></p>
<p>Recall the three layers in CSS: the user agent stylesheet, the user stylesheet, and the author stylesheet. We have direct access to the author styles, residing in the layer capable of overriding all others.</p>
<p>The notable enhancement brought about by cascading layers is the ability to create new layers within the author stylesheet, as demonstrated in the previous example.</p>
<p>The fundamental principle governing layering is that any CSS code within a layer possesses lower specificity compared to any CSS code outside a layer. This explains why the struggle to apply the <code>background-color</code> is won by the <code>.button</code> class outside the layer. Unlayered selectors consistently maintain higher specificity than their layered counterparts.</p>
<h2 id="heading-creating-multiple-layers">Creating Multiple Layers</h2>
<p>The intrigue of layering intensifies when multiple layers come into play, allowing you to organize your CSS effectively. Managing multiple layers adds another dimension to ordering specificity, involving considerations such as the sequence in which layers are created, their initial appearance, and the ability to specify the desired order of layers.</p>
<p>In this section, we will utilize the initial HTML code and make adjustments to the CSS to comprehensively grasp the outcomes of layers in various scenarios.</p>
<h3 id="heading-the-effect-of-sequence">The Effect of Sequence</h3>
<p>When employing cascade layers and encountering two <code>@layer</code> declarations, the declaration that appears last will assume higher specificity and be applied, mirroring the standard order in the CSS cascade. Let's implement these changes to the CSS we've been using:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
}

<span class="hljs-keyword">@layer</span> button {
  <span class="hljs-selector-class">.button</span> {
    <span class="hljs-attribute">display</span>: inline-block;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4caf50</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  }
}

<span class="hljs-keyword">@layer</span> navigation {
  <span class="hljs-comment">/* Navigation Bar */</span>
  <span class="hljs-selector-tag">nav</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">text-align</span>: center;
  }

  <span class="hljs-selector-class">.nav-list</span> <span class="hljs-selector-tag">a</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> <span class="hljs-number">15px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  }
}

<span class="hljs-comment">/* Hero Section */</span>
<span class="hljs-selector-class">.hero-section</span> {
  <span class="hljs-attribute">background-size</span>: cover;
  <span class="hljs-attribute">background-position</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#4caf50</span>;
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">100px</span> <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">48px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">40px</span>;
}
</code></pre>
<ul>
<li><p>In the updated CSS code above, I introduced another layer declaration, <code>@layer button</code>, and placed the <code>.button</code> class inside it. Consequently, the <code>@layer button</code> comes last, and all styles within the navigation layer, <code>@layer navigation</code>, will be preferentially applied.</p>
</li>
<li><p>As a result, our buttons now exhibit a background color of <code>#fff</code>, as illustrated in the image below:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736180904640/d934029d-14e5-4256-9e38-8ca7a0bb8e4d.gif" alt class="image--center mx-auto" /></p>
<p>A crucial point to remember is that when a selector is placed inside a layer and conflicts with another selector within a different layer, the specificity preference is determined by the sequence of the layer it resides in. However, if a selector is not within any layer and competes with a selector inside a layer, the non-layered selector will be preferred. Keep this in mind as you work with cascade layers.</p>
<h3 id="heading-first-naming-matters">First naming matters</h3>
<p>When dealing with CSS in production, you often work with various CSS files and may find yourself repeating code. In such scenarios, utilizing layers can pose challenges if you employ identical layer declarations across different sections.</p>
<p>Consider this scenario: If you have two layer declarations and you use one of them in another part of your CSS after initially declaring both, the subsequent declaration doesn't take precedence based on the later declaration. Instead, the crucial factor is the order in which the layers were declared in the initial instance.</p>
<p>Let's delve into the details with some code. We'll use the same HTML demo we've been working with and introduce the following modifications to the CSS.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
}

<span class="hljs-keyword">@layer</span> navigation {
  <span class="hljs-comment">/* Navigation Bar */</span>
  <span class="hljs-selector-tag">nav</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">text-align</span>: center;
  }
}

<span class="hljs-selector-class">.hero-section</span> {
  <span class="hljs-attribute">background-size</span>: cover;
  <span class="hljs-attribute">background-position</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#4caf50</span>;
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">100px</span> <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">48px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">40px</span>;
}

<span class="hljs-comment">/* Hero Section */</span>

<span class="hljs-keyword">@layer</span> button {
  <span class="hljs-selector-class">.button</span> {
    <span class="hljs-attribute">display</span>: inline-block;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4caf50</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  }
}

<span class="hljs-keyword">@layer</span> navigation {
  <span class="hljs-selector-class">.nav-list</span> <span class="hljs-selector-tag">a</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> <span class="hljs-number">15px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  }
}
</code></pre>
<ul>
<li><p>In the modified CSS code above, I relocated the <code>.nav-list a</code> class from the initial <code>navigation</code> layer declaration and placed it in the subsequent <code>navigation</code> layer declaration. To align with the explanation, the second <code>navigation</code> layer declaration won't have higher specificity than the <code>button</code> layer. This is because the timing of the declaration matters more than the sequence in which it was called.</p>
</li>
<li><p>Consequently, the browser interprets that since the <code>navigation</code> layer was declared first, it holds lower specificity than more recent layers, regardless of being declared a second time.</p>
</li>
<li><p>Observe in the image below that the color of the button in the navigation bar remains unchanged, indicating that the <code>button</code> layer maintains higher specificity and takes precedence:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736180976337/45049cb2-ee9c-492c-be22-314ef4c30f47.gif" alt class="image--center mx-auto" /></p>
<h3 id="heading-defining-orders">Defining Orders</h3>
<p>Instead of relying on mental tracking of your most recent or remote layer declaration, you have the option to explicitly define the preferred order of your layers.</p>
<p>The syntax for achieving this is:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@layer</span> layer1, layer2, layer3;
</code></pre>
<ul>
<li><p>The purpose of the snippet above is to ensure that regardless of how you later declare your layers in your CSS, it will consistently apply the CSS in the predetermined order.</p>
</li>
<li><p>In this case, the specified order for application is <code>layer1</code> with the least specificity, followed by <code>layer2</code> and then <code>layer3</code>, and so forth.</p>
</li>
</ul>
<p>Let's implement this in the ongoing demo, maintaining the HTML as is, and observe the resultant changes by making adjustments to the CSS below:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@layer</span> button, navigation;

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
}

<span class="hljs-keyword">@layer</span> navigation {
  <span class="hljs-comment">/* Navigation Bar */</span>
  <span class="hljs-selector-tag">nav</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">text-align</span>: center;
  }
}

<span class="hljs-selector-class">.hero-section</span> {
  <span class="hljs-attribute">background-size</span>: cover;
  <span class="hljs-attribute">background-position</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#4caf50</span>;
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">100px</span> <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">48px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.hero-section</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">40px</span>;
}

<span class="hljs-comment">/* Hero Section */</span>

<span class="hljs-keyword">@layer</span> button {
  <span class="hljs-selector-class">.button</span> {
    <span class="hljs-attribute">display</span>: inline-block;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4caf50</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  }
}

<span class="hljs-keyword">@layer</span> navigation {
  <span class="hljs-selector-class">.nav-list</span> <span class="hljs-selector-tag">a</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> <span class="hljs-number">15px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  }
}
</code></pre>
<ul>
<li><p>Observe that in the first line, there's a declaration specifying the order in which the layers should be applied: <code>@layer button, navigation</code>.</p>
</li>
<li><p>This signifies that the styles of the <code>navigation</code> layer should take precedence over the <code>button</code> layer in terms of specificity.</p>
</li>
<li><p>Consequently, the webpage undergoes a transformation, and the color of the buttons reverts to <code>#fff</code>, as depicted in the image below:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736181011128/1fa9772e-5997-42e2-a2c8-33e7d6214c9b.gif" alt class="image--center mx-auto" /></p>
<p>Another compelling reason for utilizing this approach is that it allows you to seamlessly integrate with frameworks without concerns about your styles being overridden by the framework's inherent styles. By explicitly defining the order of your layers, you retain control and ensure that your styles take precedence over the framework's styles. This empowers you to work cohesively within frameworks while maintaining the desired styling hierarchy.</p>
<h3 id="heading-important-layering">!important Layering</h3>
<p>As we discuss frameworks, it becomes crucial to consider the <code>!important</code> value.</p>
<p>The reason for this consideration lies in the fact that even when you arrange your layers in the order of your preferred specificity, styles can be overridden if any styling in a layer includes the <code>!important</code> tag.</p>
<p>For instance, let's consider a CSS ordering of layers:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@layer</span> layer1,layer2,layer3;
</code></pre>
<ul>
<li>Ordinarily, <code>layer3</code> is expected to possess a higher degree of specificity. However, if, in any scenario, <code>layer1</code> includes a style with an <code>!important</code> tag, that specific style will supersede a conflicting style in <code>layer2</code>. This pattern persists between <code>layer2</code> and <code>layer3</code>.</li>
</ul>
<p>Let's examine this in a practical context using HTML and CSS because, indeed, the <code>!important</code> tag is quite significant (pun intended).</p>
<pre><code class="lang-typescript">&lt;body&gt;&lt;/body&gt;
</code></pre>
<ul>
<li>To simplify, let's focus on the <code>body</code> tag.</li>
</ul>
<pre><code class="lang-css"><span class="hljs-keyword">@layer</span> framework-reset, normal-reset;

<span class="hljs-keyword">@layer</span> framework-reset {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4caf50</span> <span class="hljs-meta">!important</span>;
  }
}

<span class="hljs-keyword">@layer</span> normal-reset {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span> <span class="hljs-meta">!important</span>;
  }
}
</code></pre>
<ul>
<li><p>In the provided CSS code, there is a directive indicating the layer arrangement: <code>@layer framework-reset, normal-reset</code>.</p>
</li>
<li><p>Both layers feature conflicting styles for the <code>background-color</code> property along with an <code>!important</code> tag.</p>
</li>
<li><p>The outcome here is that <code>framework-reset</code> will have higher specificity due to the <code>!important</code> tag. The presence of an <code>!important</code> tag in <code>normal-reset</code> does not alter this result.</p>
</li>
<li><p>The key takeaway is that when the <code>!important</code> tag is introduced, the first declared layer gains higher specificity for styles associated with that tag.</p>
</li>
<li><p>Consequently, the <code>background-color: #4caf50</code> will be applied to the <code>body</code> tag. Please observe the color in the image below:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736181063947/dd31e22c-ef0d-49ff-ab4d-623247558583.gif" alt class="image--center mx-auto" /></p>
<p>Now you understand why those pesky framework bugs might arise when utilizing layers.</p>
<h3 id="heading-nesting-layers">Nesting Layers</h3>
<p>Another cool feature of utilizing layers is that, especially in large projects, you have the option to nest layers within each other. This functionality enables you to organize layers hierarchically, with one inside the other, providing the flexibility to later extend them and add additional styling.</p>
<p>Let's visualize this with a simple button.</p>
<pre><code class="lang-typescript">&lt;button <span class="hljs-keyword">class</span>=<span class="hljs-string">"button"</span>&gt;
  Hover over me
  &lt;span <span class="hljs-keyword">class</span>=<span class="hljs-string">"button-message"</span>&gt;Hey there&lt;/span&gt;
&lt;/button&gt;
</code></pre>
<ul>
<li>This includes <code>button</code> and <code>span</code> HTML elements with their respective classes.</li>
</ul>
<p>For styling these elements using layers, we can employ nested layers:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@layer</span> button {
  <span class="hljs-keyword">@layer</span> extend-button {
    <span class="hljs-selector-class">.button</span> {
      <span class="hljs-attribute">position</span>: relative;
      <span class="hljs-attribute">width</span>: <span class="hljs-number">120px</span>;
      <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">6px</span>;
      <span class="hljs-attribute">padding</span>: <span class="hljs-number">8px</span> <span class="hljs-number">12px</span>;
      <span class="hljs-attribute">display</span>: inline-block;
      <span class="hljs-attribute">border-bottom</span>: <span class="hljs-number">1px</span> dotted <span class="hljs-number">#333</span>; <span class="hljs-comment">/* Darken the dotted border color for better visibility */</span>
      <span class="hljs-attribute">cursor</span>: pointer; <span class="hljs-comment">/* Add a pointer cursor for better user experience */</span>
    }
  }
}

<span class="hljs-keyword">@layer</span> button.extend-button {
  <span class="hljs-selector-class">.button</span> <span class="hljs-selector-class">.button-message</span> {
    <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">120px</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>; <span class="hljs-comment">/* Use a dark color for the background */</span>
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">text-align</span>: center;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">6px</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">8px</span> <span class="hljs-number">12px</span>; <span class="hljs-comment">/* Slightly increase padding for better spacing */</span>

    <span class="hljs-comment">/* Position the message */</span>
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">top</span>: -<span class="hljs-number">150%</span>;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">50%</span>;
    <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translateX</span>(-<span class="hljs-number">50%</span>);
    <span class="hljs-attribute">z-index</span>: <span class="hljs-number">1</span>;
    <span class="hljs-attribute">transition</span>: opacity <span class="hljs-number">0.3s</span> ease-in-out; <span class="hljs-comment">/* Add a smooth transition for better visual appeal */</span>
  }

  <span class="hljs-selector-class">.button</span><span class="hljs-selector-pseudo">:hover</span> <span class="hljs-selector-class">.button-message</span> {
    <span class="hljs-attribute">opacity</span>: <span class="hljs-number">1</span>;
  }
}
</code></pre>
<ul>
<li><p>The provided code utilizes nested layers to structure the styling for the <code>.button</code> and <code>.button-message</code> classes.</p>
</li>
<li><p>In the first instance of nested layers, the initial layer declaration, <code>@layer button</code>, is followed by nesting <code>@layer extend-button</code> inside. This provides a method to organize layers for extending styling.</p>
</li>
<li><p>In the second instance of nested layers, <code>@layer button.extend-button</code> instructs the browser to apply additional styling within the <code>extend-button</code> layer, which is a descendant of the <code>button</code> layer.</p>
</li>
<li><p>By using nested layers, we can achieve intricate effects while maintaining an organized CSS structure.</p>
</li>
<li><p>The outcome of the code is depicted below, showcasing both the styled button and the modified button message upon hover, facilitated by the additional CSS nested with layers:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736181101094/54af9805-6657-44e8-8f60-2d8fee4109de.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, mastering the art of CSS cascading layers opens up new possibilities for web developers to efficiently manage specificity and organize their styles.</p>
<p>The traditional challenges associated with specificity issues, convoluted selectors, and the use of <code>!important</code> markers can now be addressed through the power of cascading layers.</p>
<p>By delving into the principles of cascade layering, we've gained insights into the author, user, and user agent stylesheet layers.</p>
<p>The introduction of the <code>@layer</code> keyword allows us to create specific layers within the author stylesheet, providing us with unprecedented control over the order and preference of styles.</p>
<p>Throughout this walkthrough, we explored practical scenarios, such as resolving specificity conflicts, witnessed how the sequence and order of layer declarations impact specificity, and how defining layer orders can streamline our styling process.</p>
<p>Additionally, we touched on the significance of the <code>!important</code> tag within cascading layers and the need to consider it carefully, especially when dealing with frameworks.</p>
<p>The ability to nest layers further enhances our ability to organize and structure CSS, allowing for cleaner and more maintainable code.</p>
<p>Nested layers offer a hierarchical approach to styling, enabling the creation of sophisticated effects while maintaining a clear and logical structure.</p>
<p>With these insights and practical skills, you are now a method better in navigating the complexities of frontend development with CSS, ensuring your styles are not only visually appealing but also maintainable and scalable. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Advanced Typescript]]></title><description><![CDATA[Keywords and special datatypes]]></description><link>https://xylophone.hashnode.dev/advanced-typescript</link><guid isPermaLink="true">https://xylophone.hashnode.dev/advanced-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[frontend]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Mon, 06 Jan 2025 16:19:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/U3sOwViXhkY/upload/47da8338dad98b0b1f9196d62379d9be.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Despite the fact that TypeScript (TS) is frequently touted as a superset of JavaScript (JS) that just adds type safety to existing JavaScript (JS) features, TS comes with advanced data types and features that are not available in JS. Some that will be discussed in this article are Tuples, Enums, and Interfaces, alongside special keywords.</p>
<h2 id="heading-readonly-keyword"><code>readonly</code> Keyword</h2>
<p>If you are creating type aliases and want a field to be unchangeable in any part of the code after declaring it, use the readonly keyword:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = { <span class="hljs-keyword">readonly</span> _id: <span class="hljs-built_in">number</span>; name: <span class="hljs-built_in">string</span>; email: <span class="hljs-built_in">string</span>; isPremium: <span class="hljs-built_in">boolean</span>; };
</code></pre>
<p>On the <code>_id</code> type alias, call a <code>readonly</code> operation on it. Now, if there's any attempt to mutate the <code>_id</code> after declaring it, static checking will signal an error, like in the example below:  </p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> user: User = {
    _id: <span class="hljs-number">5</span>,
    name: <span class="hljs-string">"Kelvin"</span>,
    email: <span class="hljs-string">"okuroemidouebikelvin@gmail.com"</span>,
    isPremium: <span class="hljs-literal">true</span>
};

user.name = <span class="hljs-string">"Fy"</span>;
user._id = <span class="hljs-number">78</span>; <span class="hljs-comment">// Error !!!</span>
</code></pre>
<h2 id="heading-question-marks">Question Marks</h2>
<p>When defining type aliases, certain parameters can be optional.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
    <span class="hljs-keyword">readonly</span> _id: [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>];
    name: <span class="hljs-built_in">string</span>;
    email: <span class="hljs-built_in">string</span>;
    isPremium: <span class="hljs-built_in">boolean</span>;
    credcardDetails?: <span class="hljs-built_in">number</span>; <span class="hljs-comment">// Optional alias</span>
};
</code></pre>
<ul>
<li>Even if <code>credcardDetails?</code> is not specified when using the <code>User</code> type alias, no static checking is triggered. The question mark simply indicates that it is optional.</li>
</ul>
<h2 id="heading-combining-types">Combining Types</h2>
<p>Type aliases can be combined with each other to save redundant code typing, i.e., retyping types. For example, you could have three type aliases like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> BioData = {
    name: <span class="hljs-built_in">string</span>;
    id: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> BankData = {
    accountType: <span class="hljs-built_in">string</span>;
};

<span class="hljs-keyword">type</span> CVV = {
    cvv: <span class="hljs-built_in">number</span>;
    name: <span class="hljs-built_in">string</span>;
    id: <span class="hljs-built_in">number</span>;
    accountType: <span class="hljs-built_in">string</span>;
};
</code></pre>
<ul>
<li><p>We have three type aliases, <code>BioData</code>, <code>BankData</code>, and <code>CVV</code>. <code>BioData</code> and <code>BankData</code> have type details that are wanted to create the <code>CVV</code> alias.</p>
</li>
<li><p>Copying and pasting the type details of <code>BioData</code> and <code>BankData</code> into <code>CVV</code> is not efficient and makes us repeat code, something TypeScript (TS) wants to help us avoid.</p>
</li>
</ul>
<p>So, in a case where we need the type details of another type alias to use with another type alias, we can do this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> BioData = {
    name: <span class="hljs-built_in">string</span>;
    id: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> BankData = {
    accountType: <span class="hljs-built_in">string</span>;
};

<span class="hljs-keyword">type</span> CVV = BioData &amp; BankData &amp; {
    cvv: <span class="hljs-built_in">number</span>;
};
</code></pre>
<ul>
<li>Now you don't have to copy and paste the type details of <code>BioData</code> and <code>BankData</code> into <code>CVV</code> to use it.</li>
</ul>
<p>This means that to use <code>CVV</code>, we still have to adhere to the types of all aliases mixed with it.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> firstUser: CVV = {
    name: <span class="hljs-string">"Kelvin"</span>,
    id: <span class="hljs-number">55</span>,
    accountType: <span class="hljs-string">"Checking"</span>,
    cvv: <span class="hljs-number">423</span>
};
</code></pre>
<h2 id="heading-tuples">Tuples</h2>
<p>Tuples are modified arrays. With tuples, the exact sequence of array contents can be defined based on their data types, and if this sequence is not adhered to, it can cause a bug or, in the case of TS, a static checking error.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> rgba: [<span class="hljs-built_in">number</span>, <span class="hljs-built_in">number</span>, <span class="hljs-built_in">number</span>, <span class="hljs-built_in">string</span>] = [<span class="hljs-number">53.4</span>, <span class="hljs-number">6.43</span>, <span class="hljs-number">65.5</span>, <span class="hljs-string">"transparent"</span>];
</code></pre>
<p>It is also possible to have tuple type aliases. This means that a type alias can be defined to have a preset order of data types, so any entity that uses such a type alias must define its contents as the tuple type alias.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> tupleAlias = [<span class="hljs-built_in">number</span>, <span class="hljs-built_in">boolean</span>];
<span class="hljs-keyword">const</span> user: tupleAlias = [<span class="hljs-number">46</span>, <span class="hljs-literal">false</span>];
</code></pre>
<p><strong>Note:</strong> It is pertinent to note a significant flaw in tuples. Since types are defined for tuples, tuples should follow the defined type aliases, and deviation should induce TS static checking errors. However, this does not happen if the tuple is mutated with array methods.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> tupleAlias = [<span class="hljs-built_in">number</span>, <span class="hljs-built_in">boolean</span>];
<span class="hljs-keyword">const</span> user: tupleAlias = [<span class="hljs-number">46</span>, <span class="hljs-literal">false</span>];
user.push(<span class="hljs-number">56</span>); <span class="hljs-comment">// Contravenes the type alias</span>
</code></pre>
<ul>
<li><p>The last line <code>user.push(56)</code> should signal a TS static checking error since it doesn't follow the type alias <code>tupleAlias</code>, but it does not.</p>
</li>
<li><p>At the time of this article, this is an open issue in TS, and there is no solution to this behavior yet.</p>
</li>
</ul>
<h2 id="heading-enums">Enums</h2>
<p>Enums mean enumerations. Enums are used for storing different values of strings and numbers for a set of related variables. Enums aid in improving code readability.</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> seat {
    A = <span class="hljs-string">"letter A"</span>,
    B = <span class="hljs-number">2</span>,
    C = <span class="hljs-string">"Enums are great"</span>,
    D = <span class="hljs-string">"true"</span>
}

<span class="hljs-keyword">const</span> option = seat.C; <span class="hljs-comment">// Output: "Enums are great"</span>
</code></pre>
<h2 id="heading-interfaces">Interfaces</h2>
<p>In TS, an <code>interface</code> is a keyword for mainly defining how objects should be structured. It defines the properties and methods an object should have before fulfilling that. Although similar to types, it comes with its own differences that I will point out shortly. This is how to define interfaces:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> writer {
    name: <span class="hljs-built_in">string</span>;
    age: <span class="hljs-built_in">number</span>;
    showNumberofArticles(): <span class="hljs-built_in">number</span>;
}
</code></pre>
<ul>
<li>If any object or class is created with the <code>writer</code> interface, it has to contain all object fields and methods, or it will trigger a static checking error.</li>
</ul>
<p>To use an <code>interface</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> Kelvin: writer = {
    name: <span class="hljs-string">"Kelvin"</span>,
    age: <span class="hljs-number">21</span>,
    showNumberofArticles() {
        <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>;
    }
};
</code></pre>
<h3 id="heading-differences-from-type">Differences from <code>type</code></h3>
<p>The easiest to spot is that the syntax for <code>type</code> and <code>interface</code> is different.</p>
<p><code>interface</code> allows for declaration merging. Declaration merging means that two interfaces with the same name can be combined to be used for one object. So, if for some weird reason, you wanted to do that, this is how it can be done:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Person {
    name: <span class="hljs-built_in">string</span>;
    age: <span class="hljs-built_in">number</span>;
}

<span class="hljs-keyword">interface</span> Person {
    gender: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> person: Person = {
    name: <span class="hljs-string">"John"</span>,
    age: <span class="hljs-number">30</span>,
    gender: <span class="hljs-string">"male"</span>
};
</code></pre>
<ul>
<li>However, a type cannot be changed after declaration.</li>
</ul>
<p>Interfaces can be extended with the <code>extends</code> keyword. This allows for the creation of hierarchies and inheritance of interface properties:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Animal {
    name: <span class="hljs-built_in">string</span>;
    eat(): <span class="hljs-built_in">void</span>;
}

<span class="hljs-keyword">interface</span> Dog <span class="hljs-keyword">extends</span> Animal {
    breed: <span class="hljs-built_in">string</span>;
    bark(): <span class="hljs-built_in">void</span>;
}

<span class="hljs-keyword">const</span> dog: Dog = {
    name: <span class="hljs-string">"Buddy"</span>,
    breed: <span class="hljs-string">"Labrador"</span>,
    eat() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is eating.`</span>);
    },
    bark() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is barking.`</span>);
    }
};
</code></pre>
<ul>
<li><p>The <code>Animal</code> interface is created, and the <code>Dog</code> interface inherits its specifications through the <code>extends</code> keyword.</p>
</li>
<li><p>The <code>dog</code> variable then uses the <code>Dog</code> interface and has to satisfy all the requirements for both <code>Animal</code> and <code>Dog</code>.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>TypeScript's advanced features, such as <code>readonly</code> keywords, optional parameters, type combinations, tuples, enums, and interfaces, empower developers to write cleaner, safer, and more maintainable code. These tools go beyond what JavaScript offers, enhancing both productivity and scalability in modern development. While some issues, like tuple mutation, remain unresolved, TypeScript continues to evolve, cementing its place as a powerful asset for developers looking to enforce strong typing and reduce runtime errors. Whether you're just starting with TypeScript or refining your skills, leveraging these features will undoubtedly improve your development workflow.</p>
]]></content:encoded></item><item><title><![CDATA[CSS Nesting]]></title><description><![CDATA[Tips and Tricks for Efficient Styling]]></description><link>https://xylophone.hashnode.dev/css-nesting</link><guid isPermaLink="true">https://xylophone.hashnode.dev/css-nesting</guid><category><![CDATA[frontend]]></category><category><![CDATA[CSS3]]></category><category><![CDATA[Design]]></category><category><![CDATA[webdev]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Mon, 09 Dec 2024 07:00:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/4MS2B8VcpXM/upload/0fafaf9870ff173a688347284f4f92bf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-prerequisite">Prerequisite</h2>
<ul>
<li><p>Familiarity with CSS and HTML.</p>
</li>
<li><p>Strong grasp of CSS specificity.</p>
</li>
<li><p>Use an updated browser, preferably Chrome.</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>Nesting has made its way into CSS, presenting a promising development. When working with traditional CSS, dealing with selectors can be cumbersome due to repetitive use. However, CSS nesting offers a solution by allowing you to create a chain of selectors for easier access and modification. The key advantage lies in consolidating closely related selectors, enhancing code readability, and simplifying the overall coding process.</p>
<p>For those acquainted with nesting in SCSS, there might be some similarities in functionality, but there are notable differences as well. This article delves into the essential aspects of CSS nesting, including browser support, the new nesting selector symbol, and utilizing nesting with specific CSS features such as media queries.</p>
<p>Throughout the article, you'll witness real-time examples showcasing the impact of CSS nesting on HTML, observing changes in instances. Additionally, detailed explanations will accompany demonstrations of the new concepts introduced by this developer-friendly feature.</p>
<h2 id="heading-goals">Goals</h2>
<p>Upon completing this article, you will:</p>
<ul>
<li><p>Grasp the concept of nesting.</p>
</li>
<li><p>Capably utilize the nesting feature to link related selectors.</p>
</li>
<li><p>Comprehend the nuances of how nesting interacts with crucial CSS features.</p>
</li>
<li><p>Avert common issues that may arise with nesting, ensuring a smoother experience.</p>
</li>
<li><p>Have a solid understanding of the mechanics behind nesting.</p>
</li>
</ul>
<h2 id="heading-what-is-nesting">What is Nesting?</h2>
<p>Nesting is an outstanding new feature in CSS that empowers developers to create a chain or link of selectors. It introduces the use of the ampersand symbol (&amp;) to signify the levels of nesting, aiding in the organization and inheritance of selections. This concept represents an evolution in how the cascade operates in CSS.</p>
<p>The cascade, in CSS, is the process of amalgamating styles from various sources (user, author, and browser/user-agent styles) and determining the final computed styles for each element on the page. Styles are applied in a specific order, with conflicts resolved based on specificity and importance.</p>
<p>Three primary factors govern the cascade's decision-making process for style preference, listed in decreasing order of importance:</p>
<ol>
<li><p>Importance: Styles marked as important <code>!important</code> override normal styles, regardless of specificity. However, it's generally advised to use <code>!important</code> sparingly to avoid making the code difficult to maintain.</p>
</li>
<li><p>Specificity: Styles with higher specificity take precedence over styles with lower specificity. Specificity is a measure of how specific a selector is in targeting elements.</p>
</li>
<li><p>Source Order: When styles have the same specificity and importance, the order in which they appear in the style sheet determines which one takes precedence. Styles defined later in the style sheet override styles defined earlier.</p>
</li>
</ol>
<p>In addition to enabling the chaining of related selectors, CSS nesting also influences the behavior of specificity and the source order.</p>
<p>Let's delve into the syntax below for a clearer understanding of how nesting operates.</p>
<p><strong>Note:</strong> <em>The code snippet below is purely for explanatory purposes, illustrating how the syntax can be employed. It is not intended to produce an actual result.</em></p>
<p>Consider the following HTML block as an example, paying attention to the organization of the HTML elements.</p>
<pre><code class="lang-typescript">&lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"parent-selector"</span>&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p&gt;&lt;/p&gt;
&lt;/div&gt;
</code></pre>
<p>If we wanted to style the HTML above using nesting, this is how we would have done it:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.parent-selector</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
  &amp; ul {
    <span class="hljs-comment">/* Some CSS */</span>
    &amp; li {
      <span class="hljs-comment">/* Some CSS */</span>
    }
  }
  &amp; <span class="hljs-selector-tag">p</span> {
    <span class="hljs-comment">/* Some CSS */</span>
  }
}
</code></pre>
<ul>
<li><p>The <code>.parent-selector</code> represents a class selector for the main parent <code>div</code>. To nest the styling of the elements under it, simply use the ampersand symbol followed by the element and custom CSS specifications, like <code>&amp; ul</code>.</p>
</li>
<li><p>Take note that the <code>li</code> element selector is also nested inside the <code>ul</code> element selector, reflecting the HTML hierarchy where the <code>li</code> element is a descendant of the <code>ul</code>.</p>
</li>
<li><p>This feature enables a hierarchical arrangement of these selectors as long as elements and classes are organized. The nesting extends from the first element on the parent tree in the DOM to the least element in the DOM.</p>
</li>
</ul>
<h2 id="heading-how-does-nesting-work">How does Nesting Work?</h2>
<p>CSS nesting introduces the capability to embed one style rule within another, with the child rule's selector defined relative to the parent rule's selector.</p>
<p>This approach facilitates the creation of stylesheets with improved readability, enhanced modularity, and better maintainability. Such practices not only contribute to a more organized structure but also aid in minimizing the size of CSS files.</p>
<p>It's important to note that CSS nesting, unlike preprocessors like SCSS, is processed directly by the browser. This distinction can potentially lead to reduced data downloads for end-users.</p>
<p>Within the CSS nesting module, a specific syntax governs the arrangement of nested selectors. This module is instrumental in elevating the readability, modularity, and maintainability of CSS stylesheets, offering developers a powerful tool to streamline their coding practices.</p>
<p>Key takeaways from the nesting module include the introduction of a new ampersand symbol and new behaviors when working with other CSS features.</p>
<h3 id="heading-the-new-ampersand-selector">The New Ampersand Selector</h3>
<p>The new CSS nesting feature utilizes the ampersand symbol, also known as the nesting selector, to signify the level of nesting and the order of inheritance of selectors.</p>
<p>The nesting selector can be applied in various ways, primarily to indicate the inheritance of selectors. Consider the following HTML structure:</p>
<pre><code class="lang-typescript">&lt;div&gt;
  &lt;ul&gt;
    &lt;li&gt;First on the list&lt;/li&gt;
    &lt;li&gt;Second on the list&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
</code></pre>
<p>To style the <code>li</code> element, we use the cascade in CSS as follows:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">ul</span> <span class="hljs-selector-tag">li</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">300</span>;
}
</code></pre>
<ul>
<li><p>Clearly, this implies that <code>li</code> is a direct descendant of <code>ul</code>.</p>
</li>
<li><p>The <code>font-size</code> and <code>font-weight</code> are elevated, as illustrated in the image below:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668011007/e14452d6-bea4-4a15-92d6-5012b035dcfd.gif" alt class="image--center mx-auto" /></p>
<p>However, the ampersand is a novel indicator that enables the declaration of the cascade in a descending order. The following CSS will yield the same result as the example above:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">ul</span> {
  &amp; li {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">70px</span>;
    <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">300</span>;
  }
}
</code></pre>
<ul>
<li>Just as earlier, this will give the same result below:</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668014920/558e3e43-30e4-49f9-99f6-29add8e0930c.gif" alt class="image--center mx-auto" /></p>
<p>What this provides us is the ability to batch related selectors instead of writing different CSS lines to declare the cascade, as shown below.</p>
<p>Even though the ampersand is the primary symbol for indicating nesting levels, it is not always necessary. Bear with me on this, as it is one of the rules that will dictate how nesting works in CSS.</p>
<p>The ampersand symbol is not truly mandatory for nesting selectors; more importantly, any selector that has a symbol does not necessarily need the ampersand in front of it. During parsing, the browser will automatically prepend the ampersand symbol to any of your selectors. However, for the sake of consistency, you can choose to include the ampersand symbol in front of all selectors.</p>
<p>Consider the following HTML snippet, paying attention to the structure of the HTML elements.</p>
<pre><code class="lang-typescript">&lt;div&gt;
  &lt;h1&gt;Main Header&lt;/h1&gt;
  &lt;p <span class="hljs-keyword">class</span>=<span class="hljs-string">"first-paragraph"</span>&gt;
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Corrupti commodi
    eveniet qui odio dignissimos rerum? Magnam optio, perspiciatis dolor sunt
    praesentium veritatis corrupti quod, accusamus porro placeat vero blanditiis
    beatae?
  &lt;/p&gt;
  &lt;p id=<span class="hljs-string">"second-paragraph"</span>&gt;
    Lorem ipsum dolor sit, amet consectetur adipisicing elit. Voluptates
    corrupti ea tempore repudiandae saepe fugit, dolorum nam eum dolorem eveniet
    rem sed omnis hic repellat totam amet distinctio, quas excepturi?
  &lt;/p&gt;
&lt;/div&gt;
</code></pre>
<p>The initial CSS snippet below demonstrates a combination of element, class, and id selectors, utilizing the ampersand selectors to link related selectors together.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-comment">/* element selector */</span>
  &amp; h1 {
    <span class="hljs-attribute">color</span>: red;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">50px</span>;
  }

  <span class="hljs-comment">/* class selector */</span>
  &amp; <span class="hljs-selector-class">.first-paragraph</span> {
    <span class="hljs-attribute">color</span>: blue;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">40px</span>;
  }

  <span class="hljs-comment">/* id selector */</span>
  &amp; <span class="hljs-selector-id">#second-paragraph</span> {
    <span class="hljs-attribute">color</span>: green;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">30px</span>;
  }
}
</code></pre>
<ul>
<li>In this case, the selectors work seamlessly with the correct use of the ampersand symbol, and all effects will be evident. Observe the color and size changes in the header and paragraphs below:</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668086124/5d5d136a-d207-4b68-b3a9-b2198bfeeb0c.gif" alt class="image--center mx-auto" /></p>
<p>Let's modify the element selector and remove all the ampersand selectors, which will still function:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-comment">/* element selector */</span>
  h1 {
    <span class="hljs-attribute">color</span>: red;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">50px</span>;
  }

  <span class="hljs-comment">/* class selector */</span>
  <span class="hljs-selector-class">.first-paragraph</span> {
    <span class="hljs-attribute">color</span>: blue;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">40px</span>;
  }

  <span class="hljs-comment">/* id selector */</span>
  <span class="hljs-selector-id">#second-paragraph</span> {
    <span class="hljs-attribute">color</span>: green;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">30px</span>;
  }
}
</code></pre>
<ul>
<li>Despite removing the ampersand selector, all selectors continue to function as usual:</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668098845/fc447569-e288-45f7-8ad7-52e6bbe7607c.gif" alt class="image--center mx-auto" /></p>
<h3 id="heading-compound-selection">Compound Selection</h3>
<p>To create compound selectors with more than two classes, we can avoid repetition and chain these selectors together. Consider two HTML buttons, each with classes:</p>
<pre><code class="lang-typescript">&lt;a href=<span class="hljs-string">""</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"button primary"</span>&gt;Primary&lt;/a&gt;
&lt;a href=<span class="hljs-string">""</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"button secondary"</span>&gt;Secondary&lt;/a&gt;
</code></pre>
<ul>
<li><p>Two anchor elements are to be styled using two CSS classes each. The first element is styled with <code>class="button primary,"</code> and the second button is styled with <code>class="button secondary."</code></p>
</li>
<li><p>It's noteworthy that both elements share the same class, <code>button.</code></p>
</li>
</ul>
<p>Styling this without using nesting would resemble something like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.button</span><span class="hljs-selector-class">.primary</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4caf50</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
}

<span class="hljs-selector-class">.button</span><span class="hljs-selector-class">.secondary</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#3498db</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
}
</code></pre>
<ul>
<li><p>This is the conventional method of creating compound selectors.</p>
</li>
<li><p>Observe the styles for <code>.button.primary</code> and <code>.button.secondary</code> with the compound selection:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668150440/3e4eecda-68ac-4343-80e0-61d267327ed3.gif" alt class="image--center mx-auto" /></p>
<p>Then, if you wish to use nesting for the same CSS code above, you can nest both <code>.primary</code> and <code>.secondary</code> classes inside the <code>.button</code> class:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.button</span> {
  &amp;.primary {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4caf50</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  }

  &amp;<span class="hljs-selector-class">.secondary</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#3498db</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  }
}
</code></pre>
<ul>
<li><p>The <code>.button</code> class is on the same level as both <code>.primary</code> and <code>.secondary</code> classes.</p>
</li>
<li><p>Pay attention to the pseudocode, where the ampersand and class selectors are together, <code>.&amp;primary</code>, not separate as in <code>. &amp;primary</code>. This signifies that the <code>.primary</code> class is a descendant of <code>.button</code>. Thus, this is the updated approach to creating compound selections with selectors.</p>
</li>
<li><p>This will yield the same result as the example immediately above:</p>
</li>
</ul>
<p><img src alt class="image--center mx-auto" /></p>
<h3 id="heading-using-nesting-with-pseudo-element">Using Nesting with Pseudo-Element</h3>
<p>When using pseudo-elements, there's a slight nuance in how the ampersand is employed. Instead of leaving a space between the ampersand and the pseudo-element, no space is inserted between the ampersand and the pseudo-element.</p>
<p>Consider the HTML element below:</p>
<pre><code class="lang-typescript">&lt;a href=<span class="hljs-string">""</span> <span class="hljs-keyword">class</span>=<span class="hljs-string">"button"</span>&gt;Button&lt;/a&gt;
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.button</span> {
  <span class="hljs-attribute">color</span>: purple;
  <span class="hljs-attribute">text-transform</span>: uppercase;
  <span class="hljs-attribute">text-decoration</span>: none;

  &amp;:focus,
  &amp;:hover {
    <span class="hljs-attribute">background-color</span>: lightgray;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid darkgray;
  }
}
</code></pre>
<ul>
<li><p>If the ampersand were separate from the pseudo-element, the <code>:hover</code> and <code>:focus</code> effects would not have worked.</p>
</li>
<li><p>However, by correctly using the ampersand in the proper manner, we achieve the desired nested effect, as demonstrated below:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668368829/9fac2de8-70b8-4d54-9ca6-ecad87288878.gif" alt class="image--center mx-auto" /></p>
<h3 id="heading-reverse-nesting">Reverse Nesting</h3>
<p>It is also possible to represent the chain of selectors from the ground up, meaning you can choose to nest a parent selector inside a child selector and use the parent selector to control the actions of the child selector.</p>
<p>Using the HTML below:</p>
<pre><code class="lang-typescript">&lt;section <span class="hljs-keyword">class</span>=<span class="hljs-string">"hero"</span>&gt;
  &lt;p&gt;
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque ipsa
    repellendus dolores rem sit earum quibusdam alias velit sed eveniet eligendi
    dolorem qui, consequatur non fugit illo ex magnam! Temporibus.
  &lt;/p&gt;
&lt;/section&gt;
</code></pre>
<ul>
<li>Observe that the paragraph element, <code>p</code>, is a descendant of the <code>.hero</code> class, and typically, we would use the ampersand to nest <code>p</code> inside the <code>.hero</code> class.</li>
</ul>
<p>With CSS nesting, we can also style the <code>p</code> element inside the <code>.hero</code> class by nesting <code>.hero</code> inside the <code>p</code> element. Here's how to do it:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Arial"</span>, sans-serif;
}

<span class="hljs-selector-class">.hero</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f9efdb</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">30px</span>;
}

<span class="hljs-selector-tag">p</span> {
  .hero &amp; {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#638889</span>;
  }
}
</code></pre>
<ul>
<li><p>Observe in the styling for the <code>p</code> element selector, the ampersand symbol comes after the <code>.hero</code> class, and the <code>.hero</code> is nested inside <code>p</code>, despite the <code>p</code> element being a descendant selector of <code>.hero</code>.</p>
</li>
<li><p>This signifies that any <code>p</code> element inside the <code>.hero</code> should be styled with the color <code>#638889</code>.</p>
</li>
<li><p>Note the color of the <code>p</code> element in the image below as specified with nesting:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668422654/a9709c79-1870-4ec5-b84a-e0d879300e74.gif" alt class="image--center mx-auto" /></p>
<p>It's a helpful approach to consolidate related styling for one selector in a single place rather than scattering different styling specifications for the same selector throughout the stylesheet.</p>
<p>However, if you choose to employ this method, ensure that it is well-documented, as it deviates from the typical practices in CSS. Clear documentation helps maintain code transparency and aids other developers in understanding and collaborating on the project.</p>
<h3 id="heading-nesting-media-queries">Nesting Media Queries</h3>
<p>Since nesting allows a relationship with all kinds of CSS symbols, it means that we can now nest media queries!</p>
<p>Now, this is the next level of amazing. Let's examine an example using the same HTML snippet we used in the most recent example:</p>
<pre><code class="lang-typescript">&lt;section <span class="hljs-keyword">class</span>=<span class="hljs-string">"hero"</span>&gt;
  &lt;p&gt;
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque ipsa
    repellendus dolores rem sit earum quibusdam alias velit sed eveniet eligendi
    dolorem qui, consequatur non fugit illo ex magnam! Temporibus.
  &lt;/p&gt;
&lt;/section&gt;
</code></pre>
<p>And here's an updated CSS for it:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Arial"</span>, sans-serif;
}

<span class="hljs-selector-class">.hero</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f9efdb</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.25rem</span>;

  @media (<span class="hljs-attribute">min-width</span>: <span class="hljs-number">780px</span>) {
    font-size: <span class="hljs-number">2rem</span>;
  }
}

<span class="hljs-selector-tag">p</span> {
  .hero &amp; {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#638889</span>;
  }
}
</code></pre>
<ul>
<li><p>One remarkable aspect is that the media query is functional without having to rewrite the <code>.hero</code> class and nest the media query inside the rewritten class.</p>
</li>
<li><p>Observe the change in the size of the text in the hero section when the viewport is resized:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668536661/25b103b1-75f8-44de-8596-e9976872b130.gif" alt class="image--center mx-auto" /></p>
<p>Another thing to note while nesting media queries is that it can alter the order of your media queries.</p>
<p>Typically in CSS, if you make a declaration for the same selector, the specification made later takes precedence. This principle also applies when nesting media queries.</p>
<p>For instance, let's reverse the CSS specification we just used in this section:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Arial"</span>, sans-serif;
}

<span class="hljs-selector-class">.hero</span> {
  @media (<span class="hljs-attribute">min-width</span>: <span class="hljs-number">780px</span>) {
    font-size: <span class="hljs-number">2rem</span>;
  }
  <span class="hljs-selector-tag">background-color</span>: <span class="hljs-selector-id">#f9efdb</span>;
  <span class="hljs-selector-tag">padding</span>: 50<span class="hljs-selector-tag">px</span>;
  <span class="hljs-selector-tag">font-size</span>: 1<span class="hljs-selector-class">.25rem</span>;
}

<span class="hljs-selector-tag">p</span> {
  .hero &amp; {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#638889</span>;
  }
}
</code></pre>
<ul>
<li><p>We placed the <code>@media</code> declaration before the other CSS declaration for the <code>.hero</code> class.</p>
</li>
<li><p>Observe that the result below remains the same as the previous example, and the later <code>font-size: 1.25rem</code> declaration does not take precedence:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668545642/bc72758b-4864-45c8-98de-4a56462287e4.gif" alt class="image--center mx-auto" /></p>
<p>The reason for this behavior is that when the browser parses through nested CSS code, regular declarations are hoisted to the top before nested declarations.</p>
<p>So, if, for example, you wanted regular declarations to take precedence in the code snippet above and made them the most recent, they wouldn't. Why? Because the browser would hoist the normal declarations above the nested media query, and the nested media query would then take precedence. Therefore, be aware that this can be one of those things that could cause unexpected issues.</p>
<p>Let's visualize this. If the CSS were written in the standard way without nesting, it could have been like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Arial"</span>, sans-serif;
}

<span class="hljs-selector-class">.hero</span> {
  @media (<span class="hljs-attribute">min-width</span>: <span class="hljs-number">780px</span>) {
    font-size: <span class="hljs-number">2rem</span>;
  }
}

<span class="hljs-selector-class">.hero</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f9efdb</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.25rem</span>;
}

<span class="hljs-selector-tag">p</span> {
  .hero &amp; {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#638889</span>;
  }
}
</code></pre>
<ul>
<li><p>Observe that there are two <code>.hero</code> selectors. The first one includes a media query for the size, and the second <code>.hero</code> selector contains another specification for the font size, <code>font-size: 1.25rem</code>.</p>
</li>
<li><p>As per CSS rules, the second selector would take precedence and impact the size, in contrast to when we used nesting where CSS hoisted back the regular declarations to the top, and the media query took precedence:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668663257/57cd37e9-9393-4503-bbb5-3c071683f999.gif" alt class="image--center mx-auto" /></p>
<p>Observe that the text font above is smaller, confirming that nesting alters how the cascade works.</p>
<h2 id="heading-readability-trade-offs">Readability Trade Offs</h2>
<p>When nesting is implemented, there is a significant increase in specificity, which can be advantageous or, on the flip side, a bit complex. This is why some people suggest that it's better to make all selectors classes.</p>
<p>However, opting for all selectors as classes can result in CSS being spread out, potentially leading to repetitive typing. As emphasized in this article, chaining selectors provides a middle ground, making them easily scrutinized.</p>
<p>One major trade off of nesting is that when elements are nested two or three levels deep, it can introduce complexity, making it challenging to read and understand how selectors are related. This complexity can potentially lead to bugs, defeating the purpose of nesting. Something like the example below would be impractical and potentially problematic:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.div</span> {
  &amp; nav {
    &amp; ul {
      <span class="hljs-comment">/* Some CSS */</span>
      &amp; li {
        <span class="hljs-comment">/* Some CSS */</span>
        &amp; a {
          <span class="hljs-comment">/* Some CSS */</span>
        }
      }
    }
  }
}
</code></pre>
<p>Certainly, that structure seems quite chaotic. Specificity is unnecessarily heightened in this scenario, resulting in unreadable code.</p>
<h2 id="heading-nesting-specificity">Nesting Specificity</h2>
<p>Another quirk that comes with nesting is that it can mess around with specificity.</p>
<p>Let's take a look at the HTML sample below:</p>
<pre><code class="lang-typescript">&lt;section <span class="hljs-keyword">class</span>=<span class="hljs-string">"hero"</span>&gt;
  &lt;p&gt;
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque ipsa
    repellendus dolores rem sit earum quibusdam alias velit sed eveniet eligendi
    dolorem qui, consequatur non fugit illo ex magnam! Temporibus.
  &lt;/p&gt;
&lt;/section&gt;
&lt;section id=<span class="hljs-string">"body"</span>&gt;
  &lt;h1 <span class="hljs-keyword">class</span>=<span class="hljs-string">"body-header"</span>&gt;Welcome to Open Replay&lt;/h1&gt;
  &lt;p&gt;
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque ipsa
    repellendus dolores rem sit earum quibusdam alias velit sed eveniet eligendi
    dolorem qui, consequatur non fugit illo ex magnam! Temporibus.
  &lt;/p&gt;
  &lt;p&gt;
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum
    consequatur quae sint a animi. Laborum delectus, aspernatur harum repellat
    provident architecto? Reiciendis nostrum ullam soluta, ipsum architecto
    eligendi libero saepe.
  &lt;/p&gt;
&lt;/section&gt;
</code></pre>
<ul>
<li>We have two <code>section</code> elements, one with a <code>.hero</code> class, and another with an id of <code>body</code> and an additional class of <code>body-header</code>. Those are the selectors I want you to take note of.</li>
</ul>
<p>And the CSS sample for styling it is:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* Reset some default margin and padding for consistent styling */</span>
<span class="hljs-selector-tag">body</span>,
<span class="hljs-selector-tag">h1</span>,
<span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
}

<span class="hljs-comment">/* Apply a dark theme to the hero section */</span>
<span class="hljs-selector-class">.hero</span> {
  <span class="hljs-attribute">background-color</span>: black;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">text-align</span>: left;
}

<span class="hljs-comment">/*Both a class and an ID are used together*/</span>
<span class="hljs-selector-class">.hero</span>,
<span class="hljs-selector-id">#body</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">40px</span>;
  &amp; p {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#555</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.1em</span>;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
  }

  <span class="hljs-comment">/* Header 1 styling */</span>
  <span class="hljs-selector-tag">h1</span> {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2.5em</span>;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
  }
}

<span class="hljs-selector-class">.body-header</span> {
  <span class="hljs-attribute">color</span>: blue;
}

<span class="hljs-comment">/* Style the introduction section */</span>
<span class="hljs-selector-class">.body</span> {
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">800px</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
}
</code></pre>
<ul>
<li><p>At some point, both the class and id selectors, <code>.hero</code> and <code>#body</code>, are sharing the same styles and contain a nested <code>h1</code> element.</p>
</li>
<li><p>However, beneath the nested combination of <code>.hero</code> and <code>#body</code>, there is a newer specification for the header with a class of <code>.body-header</code>. So, why hasn't the header changed to the color blue in the image below?</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733668708562/34b601d4-07f1-46db-ae6c-3d2e0f0fed2f.gif" alt class="image--center mx-auto" /></p>
<p>Remember, in CSS, the latest declaration between two selectors with the same effect is supposed to be applied to HTML.</p>
<p>However, the issue in the CSS above arises because, instead of the browser considering the latest declaration for an element, it is ignoring this principle. It instead looks for the highest specificity among these selectors, and in this case, the nesting selectors have the highest specificity.</p>
<p>ID selectors have the highest specificity among all kinds of CSS selectors. In the CSS code snippet where one of the nesting selectors is an ID, the nesting selector will take precedence despite the presence of a later CSS declaration for the same action.</p>
<p>In essence, if your nesting selectors contain declarations that clash with declarations of another selector, the nesting selector will take precedence if it has a selector of higher specificity.</p>
<p>Therefore, it's essential to carefully review your code, as unintended consequences can arise from such scenarios.</p>
<h2 id="heading-browser-support">Browser support</h2>
<p>As of the time of writing this article, nesting has <a target="_blank" href="https://caniuse.com/?search=nesting">combined full and partial support</a> of over 80%. It is supported on all major browsers, including Chrome, Edge, Safari, Firefox, and Opera.</p>
<p>However, it's crucial to note that some versions of these browsers do not support nesting. It's important to be aware that if your userbase includes these versions, it could potentially break your site. Therefore, it is advisable to conduct research on the versions used by your audience before incorporating nesting into your code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, understanding and utilizing CSS nesting can significantly enhance the structure and readability of your stylesheets.</p>
<p>With features like the new ampersand selector, compound selection, and the ability to nest pseudo-elements and media queries, developers have powerful tools at their disposal.</p>
<p>However, it's crucial to weigh the readability tradeoffs that come with nesting, as excessive indentation may hinder code maintenance. Additionally, the specificity introduced by nesting should be considered to avoid unintended style conflicts.</p>
<p>While nesting offers a more organized approach, it's essential to strike a balance that fosters clarity and maintainability without sacrificing specificity control. Finally, keeping an eye on browser support is crucial when implementing nesting features, ensuring a consistent user experience across different platforms.</p>
<p>By carefully considering these aspects, developers can harness the benefits of CSS nesting while mitigating potential challenges, ultimately contributing to more efficient and maintainable front end practices.</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#understanding_the_cascade">All you need to know about the CSS cascade</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Code Splitting for React]]></title><description><![CDATA[Creating Efficient Front End Applications]]></description><link>https://xylophone.hashnode.dev/code-splitting-for-react</link><guid isPermaLink="true">https://xylophone.hashnode.dev/code-splitting-for-react</guid><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><category><![CDATA[React]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[best practices]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Mon, 02 Dec 2024 07:00:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UYsBCu9RP3Y/upload/87a163f3a0b8512d210714576910889b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-prerequisite">Prerequisite</h2>
<ul>
<li><p>Familiarity with <a target="_blank" href="https://www.w3schools.com/react/react_router.asp">React Router</a></p>
</li>
<li><p>Proficiency in using DevTools, preferably in Chrome.</p>
</li>
<li><p>Installation of the latest version of Node is required.</p>
</li>
<li><p>Understanding of <a target="_blank" href="https://react.dev/reference/react/Suspense">React Suspense</a> concept.</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>When leveraging React to create your high-quality application, the anticipation is for enhanced speed compared to traditional JavaScript development. However, if your React app encounters sluggish performance, a straightforward and library-light approach to address this is through code splitting.</p>
<p>This article delves into the concept of code splitting, elucidating what it entails and guiding you on its implementation to optimize the efficiency of your applications. Explore the benefits of code splitting and learn how to seamlessly integrate it into your React projects for improved performance.</p>
<h2 id="heading-goals">Goals</h2>
<p>This article aims to:</p>
<ul>
<li><p>Describe the process of code splitting.</p>
</li>
<li><p>Provide a clear understanding of what code splitting is in the context of React applications.</p>
</li>
<li><p>Offer practical insights into implementing code splitting in React applications.</p>
</li>
<li><p>Highlight the advantages and benefits of incorporating code splitting into React applications.</p>
</li>
</ul>
<h2 id="heading-understanding-code-splitting">Understanding Code Splitting</h2>
<p>In the realm of software development, a cardinal objective is to craft applications that are not only well-optimized but also efficient and high-performing. Despite its relatively low profile in developer discussions, code splitting has garnered increased attention, particularly with the surge of web applications and the imperative to enhance user experiences.</p>
<p>At its core, code splitting entails the dissection of a software application into modularized components, leading to tangible benefits such as improved performance and expedited load times.</p>
<p>In a more succinct definition, code splitting is a technique that strategically dissects an application's codebase into smaller, more manageable parts. The primary goal is to load only the code essential for the current user's interaction, thereby mitigating the initial load time of the application.</p>
<p>In today's digital landscape, where users demand swift and responsive interfaces, understanding and implementing code splitting is imperative. Failing to do so could result in the loss of customers and, consequently, a negative impact on business.</p>
<p>When developers build applications, a common practice involves bundling all JavaScript code into sizable files. While this method offers simplicity and facilitates easy deployment, it can lead to substantial file sizes that, in turn, hinder the initial page load and overall web app interactivity.</p>
<h3 id="heading-implenting-code-splitting">Implenting Code Splitting</h3>
<p>Code splitting can be implemented in various development environments and technologies.</p>
<p>Here are some common methods:</p>
<ul>
<li><p>Webpack: If you're using Webpack as your build tool, you can easily implement code splitting using its dynamic import feature. Webpack will automatically split your code into smaller chunks and load them on-demand when needed.</p>
</li>
<li><p>React: React, a popular JavaScript library for building user interfaces, provides a built-in mechanism for code splitting using the <code>React.lazy()</code> and <code>Suspense</code> APIs. These allow you to load components asynchronously as users navigate your application, and will be our focus for today's article.</p>
</li>
<li><p>Vue.js: Vue.js, another popular JavaScript framework, supports code splitting through dynamic imports, which lets you load components on-demand, improving the performance of your Vue applications.</p>
</li>
<li><p>Server-Side Rendering (SSR): In server-side rendered applications, you can implement code splitting by dynamically importing modules to reduce the initial server response size and improve the time-to-interactive metric.</p>
</li>
</ul>
<h2 id="heading-benefits-of-code-splitting">Benefits of Code Splitting</h2>
<p>Some worthwhile benefits of code splitting includes:</p>
<ul>
<li><p>Faster Initial Loading Time: Code splitting enables the loading of of only the essential code required for the initial page view, with this, users don't have to wait for the application to become fully usable.</p>
</li>
<li><p>Improved User Experience: Faster load times contribute to a better user experience, which leads to better satisfaction and engagement.</p>
</li>
<li><p>Lower Bandwith Consumption: Smaller code chunks mean the amount of data transferred over the network is lesser.This reduces bandwidth and potentially saves costs for both users and developers.</p>
</li>
<li><p>Efficient caching: Code splitting can improve browser caching as the only the changed or updated code chunks need to be loaded,reducing the need to download the entire application code each time.</p>
</li>
<li><p>Better Maintainability: Breaking the application into more modular parts can make the codebase more manageable and easier to maintain, test and debug.</p>
</li>
</ul>
<p>To illustrate the concept of code splitting in React today, we'll build a demo web app featuring simple toggle and alert functions. This demo will unfold in three major stages. Firstly, we'll set up our React environment using <a target="_blank" href="https://vitejs.dev/guide/">ViteJS</a> and code up the web app.</p>
<p>Afterward, we'll inspect the web app using a browser developer tool—preferably Chrome—to identify any inefficiencies. This critical analysis will help us understand the initial performance bottlenecks.</p>
<p>Following the inspection, we'll make significant changes to different components of the web app to implement code splitting. By optimizing the loading of components on-demand, we aim to observe tangible improvements in the app's overall efficiency.</p>
<h2 id="heading-part-1-building-the-initial-codebase">Part 1: Building the Initial Codebase</h2>
<p>Since this is a very practical topic, I felt it would be best to orient this article to actually make a litle demo project that mirrors a standard react codebase and then dissect the project while using codesplitting to make the project better in terms of efficiency.</p>
<h3 id="heading-setting-up">Setting up</h3>
<p>Let's set up the ViteJS environment.</p>
<ol>
<li>Before we begin, ensure that you have the <a target="_blank" href="https://nodejs.org/en">latest version of Node</a> installed on your computer. As of the time of writing this article, the latest version is 21.1.0. Verify your Node installation by running the following command in your terminal:</li>
</ol>
<pre><code class="lang-typescript">node --version
</code></pre>
<ol start="2">
<li>Following the Node installation, let's set up the React working environment. Execute the following command in your terminal to install Vite globally:</li>
</ol>
<pre><code class="lang-typescript">npm install -g create-vite
</code></pre>
<ol start="3">
<li>Switch to the directory where you intend to create the web app. Use the following command to navigate to your desired directory:</li>
</ol>
<pre><code class="lang-typescript">cd project-location
</code></pre>
<ul>
<li>Replace <code>project-location</code> with the location you want to make the app.</li>
</ul>
<ol start="4">
<li>Once you're inside the desired location, run the following command to create the <code>Vite-React</code> project:</li>
</ol>
<pre><code class="lang-typescript">npm create vite<span class="hljs-meta">@latest</span>
</code></pre>
<ol start="5">
<li>You'll be prompted to provide information about your project. Feel free to name it as you wish; for instance, I'll name mine <code>split-app</code>. Enter the relevant details when prompted.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077251492/86283f5c-93ae-482f-bc69-23041027eb09.gif" alt class="image--center mx-auto" /></p>
<ol start="6">
<li>When prompted about the framework, choose "react," and then select the "JavaScript" option. This ensures the project is set up with React using JavaScript.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077297959/94b277f4-8816-40d9-b84b-d1e55a23120d.gif" alt class="image--center mx-auto" /></p>
<p><strong>NOTE</strong>: <em>If you encounter challenges while selecting options using Git Bash, it's recommended to use an Integrated Development Environment (IDE) terminal such as VSCode for a smoother experience.</em></p>
<ol start="7">
<li>Execute all the commands displayed to install the necessary dependencies. This ensures that your project has all the required packages and dependencies installed.</li>
</ol>
<pre><code class="lang-typescript">cd split-app
npm install
npm run dev
</code></pre>
<ul>
<li>Running the command <code>npm run dev</code> will initiate a visual output on a specific port, confirming that the Vite-React environment is ready for use. This visual output typically indicates that your development server is up and running.</li>
</ul>
<ol start="8">
<li>Double click on the port.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077352982/a8e1204d-a423-4185-bb26-a82ff927aa8e.gif" alt class="image--center mx-auto" /></p>
<p><strong>Here's the result</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077411537/d9d4a46a-3c9b-4cbc-9ae5-771b07928112.gif" alt class="image--center mx-auto" /></p>
<h3 id="heading-making-the-web-app">Making the Web App.</h3>
<p>Now, let's start building the app. At this point, the essential packages should be installed.</p>
<ol>
<li>An important package we'll utilize is React Router, facilitating the behavior of our webpage as a Single Page Application (SPA). To install this package, use the following terminal command:</li>
</ol>
<pre><code class="lang-typescript">npm install react-router-dom@<span class="hljs-number">6</span>
</code></pre>
<ol start="2">
<li>Another crucial package will be required later for error handling. Use this command to install:</li>
</ol>
<pre><code class="lang-typescript">npm i react-error-boundary
</code></pre>
<ol start="3">
<li>Once the packages are installed, delete the default files in the <code>/src</code> folder of your app and ensure it has the following file and folder arrangement:</li>
</ol>
<pre><code class="lang-typescript">/src 
  /components
    Admin.jsx
    AdminHello.jsx
    ErrorFallback.jsx
    Header.jsx
    Home.jsx
    Layout.jsx
  App.jsx
  index.css
  main.jsx
</code></pre>
<p>These components will do these things:</p>
<ul>
<li><p><code>Admin.jsx</code>: The main component for the admin section.</p>
</li>
<li><p><code>AdminHello.jsx</code>: A component for greeting.</p>
</li>
<li><p><code>Header.jsx</code>: A component for the header section.</p>
</li>
<li><p><code>ErrorFallback.jsx</code>: Displays error messages.</p>
</li>
<li><p><code>App.jsx</code>: The combined component for your React application.</p>
</li>
<li><p><code>index.jsx</code>: Contains global styles for the entire application.</p>
</li>
<li><p><code>main.jsx</code>: The main entry point where the React application is initialized and rendered into the HTML root element.</p>
</li>
</ul>
<p>Next, let's populate all the files with code. To keep the article succinct, I won't explain every line of code but will provide a generalized idea of what each file's code will accomplish.</p>
<ol start="4">
<li>Now, let's create the main components, starting with /components/Admin.jsx.</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> AdminHello <span class="hljs-keyword">from</span> <span class="hljs-string">"./AdminHello"</span>;

<span class="hljs-keyword">const</span> Admin = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"admin"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">AdminHello</span> /&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Author<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Debitis culpa iste perspiciatis quos odit consequatur dicta nobis?
        Veritatis temporibus facere, quibusdam obcaecati molestiae possimus
        repellendus ratione? Rerum harum esse eius doloribus distinctio a neque
        sed dolore saepe voluptatem odit eligendi debitis quas molestiae ullam
        assumenda, fuga exercitationem quasi repudiandae excepturi. Ipsum, ex
        commodi. Odio minus adipisci voluptas assumenda possimus a magni
        necessitatibus libero. Quis alias dolorum dolor odio doloremque qui
        adipisci molestias eveniet eaque, consequuntur voluptatem numquam,
        aperiam beatae tenetur exercitationem cupiditate, necessitatibus nobis
        ea tempora ex. Tempore, nobis ut rem accusamus deleniti aperiam, vero
        dignissimos at, unde error sapiente eaque. At enim laudantium autem unde
        mollitia blanditiis?
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Reiciendis totam, repellendus maiores suscipit, iure unde in praesentium
        voluptatem nobis enim provident illum cumque at molestias, ratione animi
        qui possimus deserunt. Harum repudiandae excepturi beatae explicabo eius
        quis nemo eum sapiente temporibus a non debitis velit, optio distinctio
        consequuntur repellat cumque, ab possimus voluptate saepe perspiciatis
        quam. Quam aliquam, quaerat esse porro, tenetur, dolorem provident
        distinctio vero nostrum ab obcaecati? Amet voluptate animi tenetur
        praesentium ullam saepe iste a. Explicabo, distinctio temporibus!
        Laudantium quod reprehenderit dignissimos voluptates animi repudiandae,
        ad perferendis dolore a, rem voluptate repellat quasi assumenda magnam
        eaque. Sit dignissimos libero atque officiis doloribus deserunt. Eos,
        architecto!
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Tenetur, sed sequi officiis at dolor, suscipit similique esse molestiae
        ea animi consectetur aliquid facere itaque provident quasi. Adipisci
        ipsum eos odio harum necessitatibus quas corporis reprehenderit
        perspiciatis unde natus labore architecto libero saepe eaque, vero
        itaque distinctio exercitationem. Tempora qui sequi maxime dolorum
        perferendis neque minus quaerat molestias eius, libero incidunt pariatur
        similique officia ea? Eius sunt tenetur consequatur vitae, earum maxime
        assumenda dicta vero. Neque doloremque dignissimos saepe, deserunt
        officiis nam labore non rem vero, animi dolores quae magnam.
        Reprehenderit provident molestias eaque, suscipit sapiente dolores nemo
        excepturi iste nobis fugiat distinctio iure! Eius ad hic perferendis
        explicabo?
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Hic harum sed deleniti, necessitatibus eius soluta odio neque totam
        tempore, facilis quisquam molestiae optio iste quos suscipit
        reprehenderit. Assumenda molestiae, distinctio adipisci sapiente ipsa
        similique natus architecto quod quam inventore? Adipisci expedita,
        delectus quam corporis dolorum nesciunt quia illo temporibus sed alias
        accusamus dolore, debitis quidem incidunt, aliquam quod eveniet optio
        perferendis natus saepe tempora! Asperiores libero mollitia aperiam quo
        impedit possimus fugit vero? Provident eaque sapiente quis consequatur
        harum, dolores exercitationem labore quidem reiciendis quisquam
        reprehenderit accusamus ut saepe eum consequuntur eius. Corrupti, odio
        asperiores quaerat aliquam provident nesciunt quia delectus quibusdam
        eveniet accusantium, officiis vel nobis illo.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Impedit vitae temporibus non suscipit quibusdam dolor eum amet sunt,
        placeat laborum. Quis unde id ex dolor, exercitationem quae recusandae
        consequatur repellat rem eaque sint fuga ea laudantium aperiam amet
        labore sit magnam, quibusdam aliquam nisi. Earum, tempora magni dicta
        veniam, accusamus tempore quisquam esse delectus suscipit laboriosam
        labore exercitationem animi perferendis reiciendis, sapiente nemo
        deserunt eveniet ad! Illo debitis quasi voluptates dicta. Fugiat
        accusantium veritatis veniam ea praesentium quam quas sit. Animi
        consequuntur itaque, delectus enim ipsum illum dolore tempora voluptates
        voluptas. Expedita consequatur impedit architecto, quo perspiciatis
        culpa nostrum nesciunt officiis sint. Ex dolore facere animi enim
        possimus?
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Atque, omnis. Perspiciatis repudiandae est, aut molestias neque deleniti
        assumenda necessitatibus alias ea. Illo quidem fuga libero expedita,
        vitae harum reprehenderit rem cumque deleniti commodi, excepturi ducimus
        possimus eveniet ipsa. Aliquam, ullam vitae voluptatum at reiciendis
        harum rerum atque, esse earum repellendus debitis beatae, necessitatibus
        provident in eius ipsam. Provident, numquam porro. Doloribus ut fugiat
        repellendus possimus dignissimos suscipit tempore odio qui asperiores.
        Odio delectus recusandae dicta maxime atque laudantium, architecto porro
        beatae officia sit nulla fuga maiores saepe? Alias, corrupti minima id
        assumenda optio magni quidem? Qui beatae ad nam, quod excepturi
        recusandae commodi saepe deserunt perferendis accusantium magnam?
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Perspiciatis dolorum voluptates at quidem delectus modi incidunt,
        adipisci cupiditate quas? Sit inventore consectetur accusamus nihil ab
        cum autem, similique repudiandae ullam? Atque suscipit vel facere nemo
        vitae culpa magnam omnis. Iure quos officia error recusandae dolorum
        mollitia debitis magnam? Asperiores ipsa odio accusantium dolores esse
        eaque sed explicabo laudantium reiciendis dignissimos quaerat iusto
        consectetur quod animi, est omnis, molestiae ipsam molestias sequi
        provident cupiditate eligendi voluptatum corrupti perspiciatis.
        Accusamus voluptas quia cupiditate. Fugiat libero reprehenderit
        inventore fuga nisi odit suscipit voluptas, doloribus dolores distinctio
        quae aut repellat voluptatibus quam obcaecati quidem cupiditate eaque
        ex, optio rerum ducimus. Doloribus, eum.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Velit natus dolores distinctio dolorum, dicta voluptate. Officia
        consequatur fugit, unde explicabo recusandae tenetur necessitatibus
        error in repellendus, quo optio accusamus dignissimos quae deserunt sunt
        laudantium, dolore ipsa numquam eius ducimus. Repellendus a quod
        voluptatem quae aperiam molestias, dolorum ut ea id culpa praesentium,
        veritatis non et corporis eum, recusandae minima voluptas! Ad eveniet
        nihil esse maxime libero est, sed ipsam at. Totam distinctio voluptatem
        impedit et culpa, necessitatibus rem voluptate numquam beatae mollitia
        qui eligendi placeat explicabo excepturi architecto nisi unde
        praesentium autem obcaecati. Corporis, neque praesentium! Odio ipsam,
        fugiat dolor enim libero alias? Maxime quas quia possimus corrupti.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Nam non eos reiciendis aut doloremque velit ipsam repellendus aperiam
        architecto unde sint nihil reprehenderit, eaque incidunt, sed magnam
        eligendi quas rerum, tempore illo et nobis. Fugiat sint magnam
        exercitationem, eum esse voluptas, neque fuga aliquid culpa dicta in
        amet! Doloribus, consequatur voluptates explicabo excepturi veritatis
        sit cumque. Blanditiis et officia impedit? Adipisci quo ipsum dolores
        qui rerum voluptatem laudantium voluptate odio ea corporis fugit rem
        porro in possimus commodi, necessitatibus itaque mollitia obcaecati non
        debitis, expedita tempora quisquam perspiciatis excepturi. Animi neque
        totam molestias repellat illum consequatur rem, optio harum eaque ipsam,
        consequuntur, ipsum cumque delectus amet magnam excepturi?
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Eveniet iusto dolores dolore neque, sit ex voluptate consequuntur
        dignissimos repellat, modi quam. Nihil, sequi dolorem tenetur veritatis
        laboriosam debitis voluptate, distinctio facere ad aspernatur
        necessitatibus ea veniam autem at accusamus, deleniti labore! Sed
        repellendus, soluta aspernatur voluptates harum ducimus suscipit debitis
        natus earum molestias inventore ad aliquid doloremque unde quod quam.
        Repudiandae aut, aliquam natus pariatur, qui officiis quasi unde, vero
        fuga blanditiis tempora ratione eos at itaque atque quae maxime rerum
        porro? Ipsam vel laboriosam praesentium dignissimos saepe aliquam harum
        nesciunt aut doloribus fugiat. Rem veniam molestias dicta nisi adipisci
        doloremque, sed sapiente at sunt voluptatibus vero omnis.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Voluptate quis repellendus deserunt rerum necessitatibus porro sint
        ipsum vero, mollitia facere, quas nostrum vitae animi velit, blanditiis
        veritatis ullam eaque. Corrupti quia saepe, excepturi, nemo atque
        necessitatibus magni asperiores blanditiis pariatur incidunt dolores
        alias similique provident repudiandae dolorum rerum maiores ratione
        soluta dolorem voluptates, ipsum doloremque deserunt reiciendis sed?
        Atque, illum dolor ex harum nihil id illo aspernatur ea, quae, magnam
        animi consectetur qui! Quibusdam necessitatibus suscipit, consequuntur
        ipsa quam itaque excepturi quasi, voluptate placeat deserunt laboriosam
        omnis odio odit et! Quae optio similique consectetur modi aliquam,
        quisquam reprehenderit, omnis ipsum harum dolorum inventore laudantium
        fugiat nostrum odio eveniet!
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        Quod dolor repellendus quis suscipit doloremque beatae laboriosam! Nulla
        eum fuga laudantium a omnis doloribus sapiente, eius temporibus ullam
        porro, minus alias error quae. Ullam aperiam adipisci culpa harum,
        eligendi iste accusantium sit. Id magnam placeat a non beatae nobis
        architecto. Aut incidunt voluptas consequatur facilis rem illo
        temporibus architecto perspiciatis nisi ex repellat, nemo aspernatur cum
        laudantium dolorum nostrum recusandae? Expedita temporibus facilis dicta
        aspernatur quas sit soluta sint animi. Optio, perferendis numquam!
        Facere ab placeat sed vitae ullam saepe id cupiditate beatae eos natus
        voluptates non incidunt aut, dicta nulla eveniet a minima sit aperiam
        quasi? Eaque, natus?
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span>
  );
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Admin;
</code></pre>
<ol start="5">
<li>Next, let's work on <code>/components/AdminHello.jsx</code>.</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> AdminHello = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Hello, Welcome to Open Replay<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span></span>;
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AdminHello;
</code></pre>
<ul>
<li>This renders another page component.</li>
</ul>
<ol start="6">
<li>Up next<code>/components/ErrorFallback.jsx</code>.</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> ErrorFallback = <span class="hljs-function">(<span class="hljs-params">{ error, resetErrorBoundary }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"error"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Something went wrong:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">pre</span>&gt;</span>{error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">pre</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{resetErrorBoundary}</span>&gt;</span>Try again<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ErrorFallback;
</code></pre>
<ul>
<li>This is the error fall back messsage.</li>
</ul>
<ol start="7">
<li>Next up, <code>/components/Header.jsx</code>.</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> Header = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Open Replay Blog<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span>
  );
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Header;
</code></pre>
<ul>
<li>This is the header component.</li>
</ul>
<ol start="8">
<li>For the home page component, <code>/components/Home.jsx</code>.</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;

<span class="hljs-keyword">const</span> Home = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"home"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Open Replay<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/admin"</span>&gt;</span>Read more on Open Replay<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">b</span>&gt;</span>Chief Editor :<span class="hljs-tag">&lt;/<span class="hljs-name">b</span>&gt;</span> Federico Kereki
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span>
  );
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<ol start="9">
<li>Certainly, let's add code to <code>/components/Layout.jsx</code> to ensure a proper layout.</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Outlet } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
<span class="hljs-keyword">import</span> Header <span class="hljs-keyword">from</span> <span class="hljs-string">"./Header"</span>;

<span class="hljs-keyword">const</span> Layout = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Outlet</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Layout;
</code></pre>
<ol start="10">
<li>Moving on to the main application files, let's start with<code>/src/App.jsx</code>.</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Routes, Route } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
<span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Home"</span>;
<span class="hljs-keyword">import</span> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Layout"</span>;
<span class="hljs-keyword">import</span> Admin <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Admin"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Layout</span> /&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">index</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Home</span> /&gt;</span>} /&gt;

        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"admin"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Admin</span> /&gt;</span>} /&gt;
      <span class="hljs-tag">&lt;/<span class="hljs-name">Route</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Routes</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<ul>
<li>This defines routes for the application.</li>
</ul>
<ol start="11">
<li><code>/src/index.css</code> provides overall styling.</li>
</ol>
<pre><code class="lang-css"><span class="hljs-keyword">@import</span> url(<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Poppins&amp;display=swap"</span>);

* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--ADMIN-BG</span>: <span class="hljs-number">#fdf7e4</span>;
  <span class="hljs-attribute">--HOME-BG</span>: <span class="hljs-number">#faeed1</span>;
  <span class="hljs-attribute">--HEADER-COLOR</span>: <span class="hljs-number">#ded0b6</span>;
  <span class="hljs-attribute">--HEADER-BG</span>: <span class="hljs-number">#bbab8c</span>;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Poppins"</span>, sans-serif;
}

<span class="hljs-selector-id">#root</span>,
<span class="hljs-selector-tag">main</span> {
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">100vh</span>;
}

<span class="hljs-selector-tag">main</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">place-content</span>: center;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
}

<span class="hljs-selector-tag">header</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--HEADER-BG);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--HEADER-COLOR);
  <span class="hljs-attribute">position</span>: sticky;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">z-index</span>: <span class="hljs-number">1</span>;
}

<span class="hljs-selector-class">.home</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--HOME-BG);
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-class">.admin</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--ADMIN-BG);
}

<span class="hljs-selector-class">.admin</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">1rem</span>;
}
</code></pre>
<ol start="12">
<li><code>/src/main.jsx</code> gets loaded into the HTML document.</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"./index.css"</span>;
<span class="hljs-keyword">import</span> { BrowserRouter, Routes, Route } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">BrowserRouter</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/*"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">App</span> /&gt;</span>} /&gt;
      <span class="hljs-tag">&lt;/<span class="hljs-name">Routes</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">BrowserRouter</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
);
</code></pre>
<ul>
<li>This contains the main <code>react-router</code> code.</li>
</ul>
<ol start="13">
<li>After making all these changes, run the following command in your terminal and click on the local host link provided.</li>
</ol>
<pre><code class="lang-typescript">npm run dev
</code></pre>
<ul>
<li>This concludes the process, resulting in a simple homepage and a link that, when clicked, expands to reveal more content.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077519638/320bd681-1d60-4e95-bb6c-3bc171508a0b.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-part-2-identifying-bottlenecks">Part 2: Identifying Bottlenecks</h2>
<p>In my perspective, a pragmatic software engineer doesn't categorize software as strictly right or wrong but rather on a spectrum of efficiency. While there's nothing inherently flawed with the demo as it functions perfectly, its efficiency might be optimized further.</p>
<p>The crux of our discussion in this article is that if the client doesn't require the full code at a specific time, it's not best practice to provide everything at once. It's crucial to deliver only the necessary code to the client at a given point, emphasizing the importance of code splitting for enhanced efficiency and a more streamlined application.</p>
<p>We want to address an issue with the <code>split-app</code>, our example React app. Currently, upon loading, all components, including <code>/components/Admin.jsx</code> and <code>/components/AdminHello.jsx</code>, are being loaded. However, these components are intended to be loaded only when an admin is using the app, not on the initial load.</p>
<p>Our objective with code splitting is to prevent the loading of the admin components until the "read more" link is clicked. To visualize these inefficiencies, let's turn to DevTools:</p>
<ol>
<li>Open chrome developer tools by either right-clicking on the demo and choosing "inspect" or option or pressing Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux).</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077557185/df8655e7-6079-4d0d-a1c1-5b2b81c525d7.gif" alt class="image--center mx-auto" /></p>
<ol start="2">
<li>Click on the "Sources" option, and right-click for a moment on the refresh option. Then, select "Empty Cache and Hard Reload." This ensures a fresh start, clearing any cached data that might affect the loading behavior of the application.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077617494/3e23e556-e95c-42d6-be52-8927afb5165b.gif" alt class="image--center mx-auto" /></p>
<ol start="3">
<li>After refreshing the page, navigate to the <code>src</code> folder and then to the <code>components</code> folder. Observe the files, and you'll notice that both <code>Admin.jsx</code> and <code>AdminHello.jsx</code> are present. As you are aware, these files should only be loaded on demand, highlighting the current inefficiency we aim to address with code splitting.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077687237/7a3f3f9f-a676-47db-96d6-2f81004966ca.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-part-3-code-splitting-with-lazy-loading">Part 3: Code Splitting with Lazy Loading</h2>
<p>Now, let's optimize our application. Keep in mind that the objective of this demo is to ensure that the files <code>/src/components/Admin.jsx</code> and <code>/src/components/AdminHello.jsx</code> are loaded only when the "read more" link is clicked. This is the essence of code splitting—to load specific components on-demand for a more efficient application. Turn over to <code>/src/App.jsx</code> because that is the file where we would be splitting the application. And make changes to the file like this:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Routes, Route, useNavigate } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
<span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Home"</span>;
<span class="hljs-keyword">import</span> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Layout"</span>;
<span class="hljs-comment">// import Admin from "./components/Admin"</span>
<span class="hljs-keyword">import</span> { ErrorBoundary } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-error-boundary"</span>;
<span class="hljs-keyword">import</span> ErrorFallback <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/ErrorFallback"</span>;
<span class="hljs-keyword">import</span> { lazy, Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Admin = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">"./components/Admin"</span>));

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> navigate = useNavigate();

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Layout</span> /&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">index</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Home</span> /&gt;</span>} /&gt;

        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span>
          <span class="hljs-attr">path</span>=<span class="hljs-string">"admin"</span>
          <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>
            &lt;<span class="hljs-attr">ErrorBoundary</span>
              <span class="hljs-attr">FallbackComponent</span>=<span class="hljs-string">{ErrorFallback}</span>
              <span class="hljs-attr">onReset</span>=<span class="hljs-string">{()</span> =&gt;</span> navigate("/")}
            &gt;
              <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">Admin</span> /&gt;</span>
              <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">ErrorBoundary</span>&gt;</span>
          }
        /&gt;
      <span class="hljs-tag">&lt;/<span class="hljs-name">Route</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Routes</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In the previous version of this file, <code>&lt;Route path="admin" element={&lt;Admin /&gt;}/&gt;</code> is responsible for handling and granting access to the admin page.</p>
<p>To ensure that the admin pages are loaded in the browser only when the admin link is clicked, here are the changes made in <code>src/App.jsx</code>:</p>
<ul>
<li><p><code>import { Routes, Route, useNavigate } from "react-router-dom"</code>: This line imports specific components and functions from the <code>react-router-dom</code> library for setting up routing in the application.</p>
</li>
<li><p>The newly added import statements <code>import { ErrorBoundary } from "react-error-boundary"</code> and <code>import ErrorFallback from "./components/ErrorFallback"</code> are part of React's system for catching errors anywhere in the component tree and logging those errors.</p>
</li>
<li><p>Meanwhile, <code>import { lazy, Suspense } from "react"</code> are modules used for lazy loading and code splitting. Lazy loading defers the loading of certain assets until they are needed.</p>
</li>
<li><p>This line <code>const Admin = lazy(() =&gt; import('./components/Admin'))</code> uses the <code>lazy</code> module from React to lazy load the <code>Admin</code> component.</p>
</li>
<li><p>This component <code>&lt;ErrorBoundary FallbackComponent={ErrorFallback} onReset={() =&gt; navigate('/')}&gt;</code> is the standard way of using the <code>ErrorBoundary</code> and <code>ErrorFallback</code> modules to handle errors. The <code>navigate</code> function redirects to the home page in case of errors.</p>
</li>
<li><p><code>&lt;Suspense fallback&gt;</code> uses the <code>Suspense</code> module from React to enable lazy loading. The <code>fallback</code> prop is required and represents the UI to show while the main UI components are being lazy loaded. However, since it isn't in the scope of this article, I chose to not create a proper fallback UI.</p>
</li>
</ul>
<p>To confirm if our changes worked:</p>
<ol>
<li><p>Exit your current thread on your terminal using CTRL+C. Save your changes.</p>
</li>
<li><p>Restart the server with this command, and click on the port:</p>
</li>
</ol>
<pre><code class="lang-typescript">npm run dev
</code></pre>
<ol start="3">
<li>Open developer tools, go to the "Sources" option, and refresh with the "Empty Cache and Hard Reload" option.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077743473/f1380aca-14a0-42eb-8835-f00d0b951051.gif" alt class="image--center mx-auto" /></p>
<ol start="4">
<li>Toggle the <code>src</code> folder in DevTools, and observe that the admin files <code>/components/Admin.jsx</code> and <code>/components/AdminHello.jsx</code> are absent. This behavior occurs due to lazy loading.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077789715/b6beb154-9363-48d7-ae2f-8f29019d0958.gif" alt class="image--center mx-auto" /></p>
<ol start="5">
<li>Now, if you click the link on the homepage, <code>/components/Admin.jsx</code> and <code>/components/AdminHello.jsx</code> will be loaded in the browser.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733077835457/0e0516e5-bcd7-4e8f-bc8d-e8e1e4f89f57.gif" alt class="image--center mx-auto" /></p>
<p>Imagine if this were a React codebase with millions of lines of code. Consider the time it would take to load all that code at once to the client and the impact on user experience.</p>
<p>This my friend, is the magic of code splitting. With code splitting, you can selectively deliver code to users based on their interaction with your web application, optimizing performance and providing a more responsive user experience.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article has unraveled a powerful technique for enhancing the efficiency of React applications.</p>
<p>We embarked on a comprehensive exploration, aiming to provide a clear understanding of what code splitting entails in the context of React development.</p>
<p>The goals included describing the process of code splitting, highlighting its advantages,and offering practical insights into its implementation.</p>
<p>By breaking down the complexities of code splitting, we've illustrated its potential to transform React applications, especially in scenarios where loading large volumes of code upfront could hinder user experience.</p>
<p>The practical demo, focusing on a web app example, allowed us to witness firsthand how code splitting can be a game-changer. Through strategic implementation, we ensured that components are loaded only when necessary, optimizing performance.</p>
<p>Code splitting isn't just a technique; it's a solution to the challenge of delivering large-scale applications without sacrificing speed. As we conclude this exploration, consider incorporating code splitting into your React projects, unlocking the magic of efficient and responsive user experiences.</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p><a target="_blank" href="https://vitejs.dev/guide/">Vite documentation</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/KelvinOkuroemi/split-app">Completed Demo</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Making Consistent Web Layouts With Subgrid]]></title><description><![CDATA[You should have a basic understanding of HTML and CSS. A solid grasp of CSS Grid is necessary. Make sure you have an updated browser, preferably Chrome…]]></description><link>https://xylophone.hashnode.dev/making-consistent-web-layouts-with-subgrid</link><guid isPermaLink="true">https://xylophone.hashnode.dev/making-consistent-web-layouts-with-subgrid</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[CSS]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Sat, 05 Oct 2024 23:00:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/8Olwvi2LW0M/upload/118738a42ad29593695d9ca662f8fecd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p>You should have a basic understanding of HTML and CSS.</p>
</li>
<li><p>A solid grasp of CSS Grid is necessary.</p>
</li>
<li><p>Make sure you have an updated browser, preferably Chrome.</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>While CSS subgrid has been around for quite some time, it only recently became stable in the past few months. In case you're unfamiliar with subgrid, it's essentially a version of the CSS grid layout designed to simplify handling the quirky behaviors often encountered with grids.</p>
<p>Have you ever faced issues with elements not aligning as expected or elements overlapping each other at different screen sizes? CSS subgrid offers a more effective and straightforward solution to address these kinds of problems.</p>
<p>This article will guide you through the features that CSS subgrid brings to the design table and demonstrate how it can solve design problems that might be challenging to tackle directly with a standard grid.</p>
<h2 id="heading-goals">Goals</h2>
<p>By the end of this article, you will have a clear understanding of:</p>
<ul>
<li><p>The underlying issue with the standard grid.</p>
</li>
<li><p>The concept of subgrid and its practical application.</p>
</li>
<li><p>The drawbacks and limitations associated with using subgrid.</p>
</li>
</ul>
<h2 id="heading-the-issue-with-grid">The Issue With Grid</h2>
<p>The problem arises when we set the display of a container to <code>grid</code>. In such cases, only the direct children of the container can access the lines, rows, columns, and areas defined on the parent container.</p>
<p>This limitation complicates the alignment of nested layouts within the children of that container with their ancestors. The well-named grid information created for the parent container becomes inaccessible to the nested layouts inside the children.</p>
<h2 id="heading-what-subgrid-has-to-offer">What Subgrid Has to Offer</h2>
<p>Unlike the standard grid, where using <code>display: grid</code> creates an independent layout for direct children, subgrid allows you to establish a new grid layout that incorporates the features of a parent layout. This means that the nested layouts within the direct children of the parent grid element can access the styles of the parent grid element.</p>
<p>The key advantage is achieving more consistent grid systems and layouts.</p>
<p>In simpler terms, without subgrid, it's not possible for indirect children to access the styling of a parent grid. This limitation hinders achieving consistent styling for both direct and indirect children in a grid layout.</p>
<p>Subgrid becomes especially valuable in scenarios where varying line lengths, influenced by user interactions with your website, might disrupt your carefully planned alignment. With subgrid, the indirect children of your main grid container (if you're using grid) can now be aligned seamlessly, offering a solution to such challenges.</p>
<h2 id="heading-how-is-subgrid-used">How is Subgrid Used?</h2>
<p>To grasp how subgrid is used, it's essential to understand the syntax provided below:</p>
<p><em>The snippets in this section serve as an explanation of how subgrid functions. A comprehensive demonstration with a visual representation of subgrid will be presented in the following paragraphs for a more practical understanding. Please note that the snippets here are for explanatory purposes only.</em></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.parent</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr [main-start] <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr [main-end] <span class="hljs-number">1</span>fr;
}

<span class="hljs-selector-class">.child</span> {
  <span class="hljs-attribute">grid-area</span>: main;
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: subgrid;
}
</code></pre>
<ul>
<li><p>The <code>.parent</code> class serves as a grid container.</p>
</li>
<li><p>It features a defined grid layout with columns set through the <code>grid-template-columns</code> property.</p>
</li>
<li><p>The columns are specified using fractional units (1fr) and are named lines <code>[main-start]</code> and <code>[main-end]</code>.</p>
</li>
<li><p>This configuration establishes a grid with seven columns, wherein the middle three columns are named <code>main-start</code> and <code>main-end</code>, each occupying one fractional unit of space.</p>
</li>
<li><p>The <code>.child</code> class represents a child grid directly nested within the parent grid.</p>
</li>
<li><p>Using <code>grid-template-columns: subgrid;</code> signifies that the columns of the descendants within this child grid should align with the columns of its parent grid. Essentially, it inherits the column definition from the parent.</p>
</li>
</ul>
<p>Please note that <code>subgrid</code> is a value of the <code>grid</code> property. Despite its name, it may sound like a standalone <code>display</code> property, but this is not the case.</p>
<p>Subgrid is utilized to define grid rows and columns. Specifically, it can be applied to <code>grid-template-columns</code> or <code>grid-template-rows</code>, and in no other scenarios. The <code>subgrid</code> keyword is exclusively used in these instances.</p>
<p>In essence, it involves delegating the responsibility of defining the grid columns or rows of the indirect element to its parent. It instructs the browser to derive the template for the indirect child from its parent, resembling a design inheritance pattern.</p>
<p>You can have a grid with automatically sized rows, while its child grid utilizes subgrid for columns or rows, potentially incorporating auto-sized columns. This flexibility allows for a versatile and adaptive layout structure, tailoring the sizing and positioning behavior according to the specific requirements of rows and columns in various parts of the layout.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.parent</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-rows</span>: auto <span class="hljs-number">1</span>fr; <span class="hljs-comment">/* First row is auto-sized, second row takes remaining space */</span>
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr; <span class="hljs-comment">/* Two columns taking equal space */</span>
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">10px</span>; <span class="hljs-comment">/* Gap between grid items */</span>
}

<span class="hljs-comment">/* Child grid using subgrid for rows and auto-sized columns */</span>
<span class="hljs-selector-class">.child</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-rows</span>: subgrid;
  <span class="hljs-attribute">grid-template-columns</span>: auto auto; <span class="hljs-comment">/* Auto-sized columns */</span>
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">5px</span>; <span class="hljs-comment">/* Gap between grid items in the child grid */</span>
}
</code></pre>
<ul>
<li>In the provided code snippet, the <code>.child</code> element demonstrates the ability to combine <code>auto</code> placement for its columns and utilize <code>subgrid</code> for its rows.</li>
</ul>
<p>Additionally, it's essential to highlight that while the line numbers of the parent grid are not inherited, the grid names are passed down. These names can be reassigned on subgrids, providing the flexibility to rename the inherited subgrid columns and rows on the fly.</p>
<h2 id="heading-solving-a-design-problem-with-subgrid">Solving a Design Problem With Subgrid</h2>
<p>In this section, we will be crafting a demo featuring a board of cards. Each card will include a text paragraph accompanied by a responsive picture to effectively showcase grid layouts. Subsequently, we will address a recurring issue with grids, proposing a solution by appropriately implementing subgrid.</p>
<ol>
<li>Create two files for the demo.</li>
</ol>
<pre><code class="lang-plaintext">/subgrid.html
/subgrid.css
</code></pre>
<ol start="2">
<li>In <code>subgrid.html</code>, we will have our main structure and some images from <a target="_blank" href="https://unsplash.com/">unsplash</a>.</li>
</ol>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!doctype <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Subgrid Demo<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"subgrid.css"</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-grid"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Lorem ipsum<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Assumenda
          recusandae maxime distinctio quos ullam incidunt.
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"//unsplash.it/501"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Omnis, veritatis odio.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Enim molestiae recusandae ut dolor sit amet consectetur adipisicing.
          odit possimus eius inventore. Quasi illo unde neque? Itaque, deleniti
          adipisci?
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"//unsplash.it/502"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Exercitationem, libero quam!<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Error maiores culpa eaque. Quam quisquam quae nostrum ipsa dolorum
          atque aperiam fugit soluta error!
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"//unsplash.it/503"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Quibusdam, recusandae odio.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Corporis laboriosam, neque est commodi architecto voluptatem, ipsam
          corrupti ullam similique eligendi hic qui natus?
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"//unsplash.it/504"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Modi, exer citat ionem dicta.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Laboriosam, aliquam tempore minus dolorem ullam et veniam asperiores,
          eveniet vitae odit itaque eligendi ducimus?
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"//unsplash.it/505"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Dolore.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Reprehenderit, labore. Lorem ipsum dolor sit amet, consectetur
          adipisicing elit. Sunt, aut. harum vitae voluptate alias saepe debitis
          quo perspiciatis, delectus fugiat modi eveniet.
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"//unsplash.it/506"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<ul>
<li><p>The HTML file is linked to our CSS, and the primary structure is a main grid, <code>&lt;div class="card-grid"&gt;</code>, containing child elements that are grids themselves, <code>&lt;div class="card"&gt;</code>.</p>
</li>
<li><p>Here's how the HTML structure should look like:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724754765070/347a8bc7-79c3-48f5-8745-704f0ea676b4.gif" alt class="image--center mx-auto" /></p>
<ol start="3">
<li>Using <code>subgrid.css</code>, style the HTML markup.</li>
</ol>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.125rem</span>;
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">1.5</span>;
}

<span class="hljs-selector-class">.card-grid</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;

  <span class="hljs-comment">/*   other styling */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-built_in">min</span>(<span class="hljs-number">90%</span>, <span class="hljs-number">60rem</span>);
  <span class="hljs-attribute">margin-inline</span>: auto;
}

<span class="hljs-selector-class">.card</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">minmax</span>(<span class="hljs-number">6ch</span>, <span class="hljs-number">20ch</span>) <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">grid-template-rows</span>: min-content <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">1em</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">3px</span> solid black;
}

<span class="hljs-selector-class">.card</span> <span class="hljs-selector-tag">h2</span> {
  <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">2</span>;
  <span class="hljs-attribute">padding-top</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">padding-right</span>: <span class="hljs-number">1em</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.75rem</span>;
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">1</span>;
}

<span class="hljs-selector-class">.card</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">2</span>;
  <span class="hljs-attribute">padding-bottom</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">padding-right</span>: <span class="hljs-number">1em</span>;
}

<span class="hljs-selector-class">.card</span> <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">grid-row</span>: <span class="hljs-number">1</span> / span <span class="hljs-number">2</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">object-fit</span>: cover;
}

<span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">100%</span>;
}

<span class="hljs-selector-tag">h2</span>,
<span class="hljs-selector-tag">h3</span>,
<span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
}

<span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">2em</span>;
  <span class="hljs-attribute">text-align</span>: center;
}
</code></pre>
<ul>
<li><p>Pay attention to the main classes, <code>.card-grid</code> and <code>.card</code>, as they house crucial grid declarations. <code>.card-grid</code> is responsible for styling the entire layout, while <code>.card</code> manages the positioning of text and images in a grid format.</p>
</li>
<li><p>Observe the proper alignment of text and images when the browser view-port is maximized:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724754816798/ae9354b7-3a8c-4249-b554-1bd33a018601.gif" alt class="image--center mx-auto" /></p>
<p>The page appears well-designed. However, note in the image below that as we resize the viewport, there is a point at the mid-size of the viewport where the images and texts of different cards are no longer aligned as they were in the largest size of the viewport:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724754946431/4a23c097-1fa5-4cc6-bc09-dccc3904accc.gif" alt class="image--center mx-auto" /></p>
<p>The reason for this misalignment is not due to any issue with our CSS but is inherent to the way the grid operates.</p>
<p>In our demo, we have a primary class for the layout, <code>.card-grid</code>, and a class for styling the direct children of the main class element, <code>.card</code>.</p>
<p>The challenge arises because the direct child elements of the <code>.card-grid</code> class align perfectly with the grid declaration of the main element's class. However, the elements styled with <code>.card</code> take their grid declarations from <code>.card-grid</code>. Due to the nature of grid operations, the indirect children – the text and images inside the <code>.card</code> <code>div</code>'s – cannot access this grid declaration.</p>
<p>Additionally, content plays a role in this misalignment. Since the text and images cannot access the grid declaration of their ancestor class, <code>.card-grid</code>, their layout is determined by the space they can occupy.</p>
<p>Take note of two of the card <code>div</code>'s and observe how text with lengthier headings occupies more space than their images, while texts with smaller headings occupy less space:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724754961317/f754601a-b82b-4c56-96b2-aabc5f2e4466.gif" alt class="image--center mx-auto" /></p>
<p>To address this issue effortlessly, we can utilize subgrid. Here's what you need to do:</p>
<ol start="4">
<li>In <code>subgrid.css</code>, make the following changes to <code>.card-grid</code> and <code>.card</code> class selectors:</li>
</ol>
<pre><code class="lang-css"><span class="hljs-selector-class">.card-grid</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">minmax</span>(<span class="hljs-number">6ch</span>, <span class="hljs-number">20ch</span>) <span class="hljs-number">1</span>fr <span class="hljs-built_in">minmax</span>(<span class="hljs-number">6ch</span>, <span class="hljs-number">20ch</span>) <span class="hljs-number">1</span>fr;

  <span class="hljs-comment">/*   other styling */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-built_in">min</span>(<span class="hljs-number">90%</span>, <span class="hljs-number">60rem</span>);
  <span class="hljs-attribute">margin-inline</span>: auto;
}

<span class="hljs-selector-class">.card</span> {
  <span class="hljs-attribute">grid-column</span>: span <span class="hljs-number">2</span>;
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: subgrid;
  <span class="hljs-attribute">grid-template-rows</span>: min-content <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">1em</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">3px</span> solid black;
}
</code></pre>
<ul>
<li><p>In the CSS code above, significant changes were made to the <code>.card-grid</code> and <code>.card</code> classes.</p>
</li>
<li><p>The <code>grid-template-columns</code> for the grid parent is modified to <code>minmax(6ch, 20ch) 1fr minmax(6ch, 20ch) 1fr;</code>. This adjustment is made in anticipation of using subgrid to make the contents of the <code>.card</code> class inherit four columns from <code>.card-grid</code>.</p>
</li>
<li><p>Within the <code>.card</code> class, the property <code>grid-column: span 2;</code> is applied, signifying that each instance of <code>.card</code> should span two columns in the parent grid, <code>.card-grid</code>.</p>
</li>
<li><p>The <code>subgrid</code> value in the <code>.card</code> class means that the child grid inherits the grid definition from its parent, which is <code>.card-grid</code>. Consequently, any content inside it should inherit the grid definition from <code>.card-grid</code>.</p>
</li>
<li><p>Note that regardless of how the page layout is resized, all the content inside <code>.card</code> elements is consistently aligned, thanks to the implementation of <code>subgrid</code>:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724755009385/5b5f678b-fe37-4c93-9863-6c905d7bc95d.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-inspecting-with-devtools">Inspecting with Devtools</h2>
<p>To ensure that our subgrid is functioning independently of the main grid, let's observe this in DevTools. I'm using Chrome, but you can use any browser that supports subgrid.</p>
<ol>
<li>Open Chrome Developer Tools on the layout demo by either right-clicking and choosing "Inspect" or pressing Option + ⌘ + J (on macOS) or Shift + CTRL + J (on Windows/Linux).</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724755078096/87a2ea89-364f-459e-97fc-ffc6364e110e.gif" alt class="image--center mx-auto" /></p>
<ol start="2">
<li>Click on the "grid" badge on the element <code>&lt;div class="card-grid"&gt;</code>. Take note in the image below that this action sets the grid overlay of red rows and columns for the grid and its direct children.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724755117270/1a19025f-5743-4bef-8b2f-450abeb0c57a.gif" alt class="image--center mx-auto" /></p>
<ol start="3">
<li>Now, on the direct children of the main grid element, click on the "subgrid" badge. Take a close look at the image below; this applies a gold overlay to the content in the <code>&lt;div class="card"&gt;</code> element.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724755154600/3e33a184-f1fa-4520-b412-7fe04f6168e4.gif" alt class="image--center mx-auto" /></p>
<p>This subgrid overlay perfectly aligns with the grid overlay, confirming that subgrid indeed ensures consistent alignment of grid layouts, from the parent grid element to the direct children and down to descendants.</p>
<h2 id="heading-subgrid-tradeoffs">Subgrid Tradeoffs</h2>
<p>Subgrid comes with a few important tradeoffs that we'll explore in this section.</p>
<p>A subgrid is closely tied to a direct parent grid, as its tracks depend on those of the parent or a subset of the parent's tracks.</p>
<p>This means careful consideration is needed for the number of items that fit into the parent grid. If there are too many items, using subgrid becomes challenging, and you may need to define new rows and columns instead.</p>
<p>A parent grid can have both explicit and implicit grid tracks. Implicit tracks are automatically created to accommodate items that exceed the explicitly defined tracks.</p>
<p>In contrast, a subgrid is less flexible because it relies on the explicit grid definition of its parent container and does not create implicit tracks.</p>
<p>However, if a parent grid track is sized using <code>auto</code>, its size is determined by the content it contains. In the case of a subgrid, the size of its tracks within the parent can impact the size of the parent's tracks if the parent's track is set to <code>auto</code>.</p>
<p>In summary, while subgrid enables the inheritance of grid layouts, it is not as accommodating as the main grid. Despite its limitations, subgrid proves beneficial for achieving more complex layouts.</p>
<h2 id="heading-browser-support">Browser Support</h2>
<p>Despite being on the waitlist for widespread stable support for a considerable duration, subgrid is now fully supported on all <a target="_blank" href="https://caniuse.com/?search=subgrid">major browsers</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, CSS subgrid emerges as a valuable addition to the toolkit of web developers seeking consistent and responsive web layouts.</p>
<p>This article delved into the essence of subgrid, exploring its role in overcoming challenges inherent in traditional grid layouts.</p>
<p>By providing a seamless way to inherit grid definitions from parent containers, subgrid enables developers to create more cohesive and adaptable designs.</p>
<p>The journey through this article highlighted the fundamental issues with grid layouts and introduced subgrid as a solution to bridge the gap between parent and child grid elements.</p>
<p>Demonstrating the syntax and usage of subgrid, we illustrated how it empowers developers to create versatile and consistent grid systems.</p>
<p>However, it's important to acknowledge the tradeoffs associated with subgrid. While it enhances consistency and alignment, subgrid is tightly coupled with its direct parent grid, making it crucial to manage the number of items within the grid to maintain its effectiveness.</p>
<p>Additionally, subgrid lacks the flexibility of implicit tracks, relying solely on the explicit grid definition of its parent container.</p>
<p>The practical application of subgrid was showcased through a demonstration, highlighting a common design problem and showcasing how subgrid resolves alignment issues. By incorporating subgrid into the CSS layout, we achieved a responsive and perfectly aligned grid structure.</p>
<p>For further exploration and learning, check out additional resources to deepen your understanding of subgrid and its capabilities. As the pursuit of perfect web layouts continue, subgrid stands out as a handy tool for achieving harmony in grid-based layouts. Happy coding !</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><a target="_blank" href="http://Web.dev">Web.dev</a> <a target="_blank" href="https://web.dev/articles/css-subgrid">article on Subgrid</a>.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[A Leaner Approach To Building Projects]]></title><description><![CDATA[To get the most out of this guide, you should have some basic knowledge of: Git GitHub Basic terminal commands Step OneCreate a main project folder: Step…]]></description><link>https://xylophone.hashnode.dev/a-leaner-approach-to-building-projects</link><guid isPermaLink="true">https://xylophone.hashnode.dev/a-leaner-approach-to-building-projects</guid><category><![CDATA[projects]]></category><category><![CDATA[buildingandlearning]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Sat, 28 Sep 2024 23:00:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/gx9HKplowQw/upload/bea765b8677af09a84fe65ae796b951e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To get the most out of this guide, you should have some basic knowledge of:</p>
<ul>
<li><p>Git</p>
</li>
<li><p>GitHub</p>
</li>
<li><p>Basic terminal commands</p>
</li>
</ul>
<h2 id="heading-setting-up-the-folder-with-git">Setting Up the Folder with Git</h2>
<p><strong>Step One</strong><br />Create a main project folder:</p>
<pre><code class="lang-bash">mkdir mainProjectFolder
<span class="hljs-built_in">cd</span> mainProjectFolder
</code></pre>
<p><strong>Step Two</strong><br />Initialize a GitHub repository locally:</p>
<pre><code class="lang-bash">git init
</code></pre>
<p><strong>Step Three</strong><br />Create an online repository for your folder (link provided).</p>
<p><strong>Step Four</strong><br />Connect the local and online repositories:</p>
<pre><code class="lang-bash">git remote add origin <span class="hljs-string">"link"</span>
</code></pre>
<p><strong>Step Five</strong><br />Add a README file within the folder:</p>
<pre><code class="lang-bash">touch readMe.md
</code></pre>
<p>A <code>README</code> file is used to describe the project and provide basic information. You should include the following in your README:</p>
<ul>
<li><p>A title</p>
</li>
<li><p>An explanation</p>
</li>
<li><p>An installation guide</p>
</li>
</ul>
<p><strong>Step Six</strong><br />Make your first push by running these commands sequentially:</p>
<pre><code class="lang-bash">git add .
</code></pre>
<pre><code class="lang-bash">git commit -m <span class="hljs-string">"commit message"</span>
</code></pre>
<pre><code class="lang-bash">git push --set-upstream origin main
</code></pre>
<h2 id="heading-folder-structure">Folder Structure</h2>
<p><strong>Step One</strong><br />Create a <code>.gitignore</code> file:</p>
<pre><code class="lang-bash">touch .gitignore
</code></pre>
<p>This file specifies which folders and files should not be uploaded to the repository.</p>
<p><strong>Step Two</strong><br />Specify the files and folders to ignore. You can find <code>.gitignore</code> templates tailored to various languages and frameworks.</p>
<p><strong>Step Three</strong><br />Create two or more folders based on how you want to organize your code. For example, if you primarily work with Webpack, you might create three folders: one for source code files, one for bundled files, and one for tests (when you start learning about testing). Inside the <code>mainProjectFolder</code>, create these folders:</p>
<pre><code class="lang-bash">mkdir src
</code></pre>
<pre><code class="lang-bash">mkdir dist
</code></pre>
<pre><code class="lang-bash">mkdir tests
</code></pre>
<p><strong>Step Four</strong><br />Create subfolders as needed. For example, if using the MVC (Model-View-Controller) pattern, you can create subfolders for model, view, and controller:</p>
<pre><code class="lang-bash">mkdir src/model
</code></pre>
<pre><code class="lang-bash">mkdir src/view
</code></pre>
<pre><code class="lang-bash">mkdir src/controller
</code></pre>
<p><strong>Step Five</strong><br />Make a commit to save your changes:</p>
<pre><code class="lang-bash">git add .
</code></pre>
<pre><code class="lang-bash">git commit -m <span class="hljs-string">"added directories"</span>
</code></pre>
<h2 id="heading-feature-boards">Feature Boards</h2>
<p>Before I established a coding system, I wasn't aware of GitHub's project boards. GitHub boards allow you to organize your projects into "To Do," "Doing," and "Done" categories.</p>
<p><strong>Step One</strong><br />Log in to your GitHub profile and navigate to the Projects section.</p>
<p><strong>Step Two</strong><br />Create a new project.</p>
<p><strong>Step Three</strong><br />Name the project and choose a view. For simplicity, I recommend using boards, though you can explore other views such as roadmaps and tables.</p>
<p><strong>Step Four</strong><br />After creating the project, you can add a new task, which will be in the <code>To Do</code> section. This will also appear as an issue. Don't forget to specify the repository by typing an <code>#</code>.</p>
<p><strong>Step Five</strong><br />With your project view ready, move tasks to <code>Doing</code> and <code>Done</code> as you work on them. This helps you stay focused. Pro tip: Avoid having more than three tasks in the <code>Doing</code> section at once.</p>
<p>With your project board set up, you can organize and prioritize your tasks more effectively rather than juggling multiple features and potentially creating buggy code.</p>
<h2 id="heading-branches">Branches</h2>
<p>To work effectively with teams, you need to understand how to use Git branches and merge features. For basic workflows, you should have a <code>feature</code> branch alongside your main branch. In Git, a branch is a copy of the main branch (usually <code>master</code> or <code>main</code>) where you can work on different features without affecting the main branch.</p>
<p><strong>Step One</strong><br />Create a new branch:</p>
<pre><code class="lang-bash">git branch release
</code></pre>
<pre><code class="lang-bash">git branch feature
</code></pre>
<p><strong>Step Two</strong><br />Switch to the new branch:</p>
<pre><code class="lang-bash">git checkout feature
</code></pre>
<p>Now you are in the <code>feature</code> branch, a copy of the main branch.</p>
<p><strong>Step Three</strong><br />Check the status of the current branch and add changes to the staging area:</p>
<pre><code class="lang-bash">git status
</code></pre>
<pre><code class="lang-bash">git add --all
</code></pre>
<ul>
<li>This adds all files in the branch.</li>
</ul>
<pre><code class="lang-bash">git commit -m <span class="hljs-string">"add a new feature in a branch"</span>
</code></pre>
<p><strong>Step Four</strong><br />Switch back to the main branch and merge the changes from the <code>feature</code> branch:</p>
<pre><code class="lang-bash">git checkout main
</code></pre>
<pre><code class="lang-bash">git merge feature
</code></pre>
<h2 id="heading-refactoring">Refactoring</h2>
<p>As you work on multiple features and technologies, consider refactoring and improving existing code. You can create a new branch specifically for refactoring. To improve your code base, focus on readability, use descriptive names for variables and functions, add comments, remove duplication (following the DRY - Don't Repeat Yourself principle), optimize time and space complexity with appropriate data structures and algorithms, and enhance error handling.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this guide, we’ve walked through the essential steps for setting up a Git-based project, organizing your folder structure, using feature boards, managing branches, and maintaining code quality through refactoring. By following these practices, you will establish a solid foundation for managing your project efficiently, whether you're working solo or as part of a team.</p>
<p>Effective use of Git and GitHub enhances your workflow, making it easier to track changes, collaborate with others, and ensure that your code remains clean and well-organized. Embracing these practices will not only streamline your development process but also improve your ability to handle complex projects and adapt to evolving requirements.</p>
<p>Remember, the key to successful project management and development is consistency. Regularly update your repository, keep your branches organized, and continually refine your code. With these strategies in place, you'll be well-equipped to tackle your projects with confidence and efficiency.</p>
]]></content:encoded></item><item><title><![CDATA[Unveiling The MVC Structure]]></title><description><![CDATA[Websites evolved in a very amazing fashion to be both stunning and cutting edge as web apps today, not just due to tools and technologies, but also due to…]]></description><link>https://xylophone.hashnode.dev/unveiling-the-mvc-structure</link><guid isPermaLink="true">https://xylophone.hashnode.dev/unveiling-the-mvc-structure</guid><category><![CDATA[software development]]></category><category><![CDATA[software architecture]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Sat, 21 Sep 2024 23:00:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/csHCIiYXeVY/upload/a60599687bfd09deb013efe6f30ccd6c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Websites evolved in a very amazing fashion to be both stunning and cutting edge as web apps today, not just due to tools and technologies, but also due to organization. The way the code sites were arranged in the last twenty years have also evolved to more robust file organization patterns. One of such is the file patterns is termed Model View Controller (MVC), and after this article, you won't need another article to start organizing your dream projects properly</p>
<h2 id="heading-pre-requisite">Pre-requisite</h2>
<ul>
<li><p>HTML</p>
</li>
<li><p>Javascript</p>
</li>
<li><p>NodeJS and ExpressJS</p>
</li>
</ul>
<h2 id="heading-model-view-controller-mvc-an-overview">Model View Controller (MVC) -An Overview</h2>
<p>MVC is just a way to organize our code bases to be more efficient and robust. It is a pattern to allow more feature implementation and iteration by many software developers while still maintaining structure and organization in our codebase. MVC entails splitting a large application into specific sections that serve different purposes under Model, View and Controller paradigms.</p>
<p><strong>Model</strong> is the section of the application that handles everything about databases, data modelling and schema. <strong>Controller</strong> is the section that receives requests from the user, interfaces with the database code of the model section, receives the data from model, and interfaces with <strong>View</strong>, the part that renders the output based on the data generated by the received from the controller.</p>
<p>The basics of MVC are:</p>
<ol>
<li><p>CONTROLLER receives request from user.</p>
</li>
<li><p>CONTROLLER sends request to MODEL section for data.</p>
</li>
<li><p>MODEL sends data back to the CONTROLLER.</p>
</li>
<li><p>CONTROLLER sends data from MODEL to VIEW.</p>
</li>
<li><p>VIEW dynamically renders an output or page based on the data it receives from CONTROLLER.</p>
</li>
<li><p>VIEW sends back output to CONTROLLER.</p>
</li>
<li><p>CONTROLLER sends response back to user.</p>
</li>
</ol>
<p>The functions of different sections are: <strong>Controller</strong>:</p>
<ul>
<li><p>Handles request flow : receives a request and sends a request to fetch data.</p>
</li>
<li><p>Never handles data logic</p>
</li>
<li><p>Sends back presentation and data to the user i.e browser</p>
</li>
</ul>
<p><strong>Model</strong>:</p>
<ul>
<li><p>Handles data logic</p>
</li>
<li><p>Interacts with database</p>
</li>
</ul>
<p><strong>View</strong>:</p>
<ul>
<li><p>Handles data presentation</p>
</li>
<li><p>A template file that dynamically renders the data sent by the controller</p>
</li>
<li><p>Sends its presentation to the controller</p>
</li>
</ul>
<p>The key thing to note is that the model and view never directly interface with each other, but through the controller.</p>
<h2 id="heading-demo">Demo</h2>
<p>The true test of learning is the ability to implement. In a real world example, if a user's browser wanted to access a login page, the controller can direct the view section to render any file based on conditions met, so it does not only serve as a data retriever from the model section, but a kind of traffic warden. For example, if a user does not have a facebook account, but tries to log in, Facebook's controller will of course ask the model to transverse its database for that user, and if the user's details do not exist, it can also tell the view page to print out an error page based on the condition that the user details does not exist.</p>
<p>Let's write some code for a mockup API using real world technologies. Before we move on, you should know that there is not one standard way of organizing MVC, you can do it with as many folders as you want as long as you separate, the backend function code, the user interface code, and database logic from each other.</p>
<h3 id="heading-without-mvc">Without MVC</h3>
<p>Normally in a project without MVC, a routing file will hold all the routes and the logic for controlling them.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {express} <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;
<span class="hljs-keyword">const</span> router = express.Router();

router.get(<span class="hljs-string">"user/all"</span>, <span class="hljs-function">(<span class="hljs-params">req,res</span>)=&gt;</span>{
    <span class="hljs-keyword">const</span> userList = User.findAll().exec();
    res.json(userList)
});

router.get(<span class="hljs-string">"user/byId/:id"</span>, <span class="hljs-function">(<span class="hljs-params">req,res</span>)=&gt;</span>{
    <span class="hljs-keyword">const</span> user = User.findById(req.params.id).exec();
    res.json(user);
})

router.post(<span class="hljs-string">"user/create"</span>,<span class="hljs-function">(<span class="hljs-params">req,res</span>)=&gt;</span>{
    <span class="hljs-keyword">const</span> User = req.body;
    User.save(<span class="hljs-function">(<span class="hljs-params">err,user</span>)=&gt;</span>{
        <span class="hljs-keyword">if</span>(err){
            res.send(err);
        } <span class="hljs-keyword">else</span>{
            res.json(user);
        }
    });
    res.json(req.body)
})
</code></pre>
<ul>
<li><p>You don't have to understand the code. It is just a snippet from a larger Node JS code.</p>
</li>
<li><p>What is you should be concerned about is how the code is structured, the router file receives requests from the user and still has all the functionality contained within the express requests.</p>
</li>
<li><p>The MVC principle urges for the router file to only receive the routing requests and call a back-end function specified in our <code>controller</code> section.</p>
</li>
</ul>
<h3 id="heading-with-mvc">With MVC</h3>
<p><strong>Step One:</strong> First of all, we have to specify our folders, to maintain clarity, I will just use the code snippet from the preceding section. We will use four folders, <code>controller</code>,<code>model</code>,<code>view</code> and <code>routes</code></p>
<pre><code class="lang-plaintext">/controller
  userController.js
/model
  userBase.js
/view
  userPage.html
/routes
  userRoute.js
</code></pre>
<ul>
<li><p>For our file structure, we added the <code>routes</code> folder to have a list of all possible routes that might correspond to the different endpoints of our <a target="_blank" href="http://API.In">API.</a> In the <code>/routes</code>, there is a <code>UserRoute</code> file for a dummy user end point.</p>
</li>
<li><p>The <code>view</code> folder will contain an output file of either dynamically generated HTML, or front-end dynamic pages like <code>ejs</code> or <code>jsx</code>. Something that can update itself to the user after receiving direction from the <code>controller</code>.</p>
</li>
<li><p>In the <code>routes</code> and <code>controller</code> sections, the <code>userRoute.js</code> and <code>userController.js</code> will work hand in hand to handle all functions for the dummy user route.</p>
</li>
</ul>
<p><strong>Step two:</strong> Change the code in the <code>routes/userRoute.js</code> to only receive requests and instead call a function from the <code>UserController</code> file in the <code>controller</code> section.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {express} <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;
<span class="hljs-keyword">const</span> router = express.Router();

<span class="hljs-keyword">import</span> UserController <span class="hljs-keyword">from</span> <span class="hljs-string">"../controller/UserController"</span>

router.get(<span class="hljs-string">"user/all"</span>,UserController.GetAllUSers)
router.get(<span class="hljs-string">"user/byId/:id"</span>,UserController.GetUSer)
router.post(<span class="hljs-string">"user/create"</span>,UserController.CreateUserProfile)
</code></pre>
<ul>
<li>The takeaway here is that we are no longer defining our functions in <code>routes/userRoute.js</code>, but only receiving the requests and calling the functions on the <code>controller/userController.js</code>.</li>
</ul>
<p><strong>Step three:</strong> Create the functions being called in the <code>userRoute.js</code> file.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// controllers/userController.js</span>

<span class="hljs-keyword">import</span> User <span class="hljs-keyword">from</span> <span class="hljs-string">"../models/user.js"</span>;

<span class="hljs-keyword">const</span> userController = {
 <span class="hljs-attr">getAllUsers</span>: <span class="hljs-keyword">async</span> (req, res) =&gt; {
   <span class="hljs-keyword">try</span> {
     <span class="hljs-keyword">const</span> userList = <span class="hljs-keyword">await</span> User.find().exec();
     res.json(userList); <span class="hljs-comment">// Take note of this res.json() method</span>
   } <span class="hljs-keyword">catch</span> (err) {
     res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">error</span>: <span class="hljs-string">"Internal Server Error"</span> });
   }
 },

 <span class="hljs-attr">getUserById</span>: <span class="hljs-keyword">async</span> (req, res) =&gt; {
   <span class="hljs-keyword">try</span> {
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> User.findById(req.params.id).exec();
     res.json(user);
   } <span class="hljs-keyword">catch</span> (err) {
     res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">error</span>: <span class="hljs-string">"Internal Server Error"</span> });
   }
 },

 <span class="hljs-attr">createUser</span>: <span class="hljs-keyword">async</span> (req, res) =&gt; {
   <span class="hljs-keyword">try</span> {
     <span class="hljs-keyword">const</span> newUser = <span class="hljs-keyword">new</span> User(req.body);
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> newUser.save();
     res.json(user);
   } <span class="hljs-keyword">catch</span> (err) {
     res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">error</span>: <span class="hljs-string">"Internal Server Error"</span> });
   }
 },
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> userController;
</code></pre>
<ul>
<li><p>First of all, notice that we are importing a <code>User</code> model from with this line <code>import User from "../models/userBase.js";</code></p>
</li>
<li><p>This <code>User</code> model contains all the data operations and logic for this specific feature, that can be used in the <code>controller</code> section.</p>
</li>
<li><p>If we have a feature that warrants us to save some data, we use the <code>User</code> model, like on this line <code>const userList = await User.find().exec();</code></p>
</li>
<li><p>Then the most important thing is that all the backend functions,<code>getAllUsers</code>,<code>getUserById</code>, and <code>createUser</code> required for the <code>user</code> route is being called in the controller section, and interacting with the model section and exported to the routes section.</p>
</li>
<li><p>The <code>res.json()</code> method is used to store the response gotten from the model section and send it to the view section. (More on JSON here).</p>
</li>
<li><p>By now you should be noticing a trend, that the controller section is the only section interacting with the route and model sections, and will do the same for the view section. So the MVC pattern only warrants that no other section should interface with each other, without passing through the controller as the middleman.</p>
</li>
</ul>
<p><strong>Step four:</strong> To keep things simple, let's say you want to render a new webpage in HTML due to data sent from the model section to the controller section, you should be faced with two problems, the design of the webpage, which is the hard part, and how to send a response to the view section from the controller which is the easy part. Let's do the easy part below:</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- views/userPage.html --&gt;</span>

<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>User List<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>User List<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user-list"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-comment">// Fetch user data from the server</span>
    fetch(<span class="hljs-string">"/users/all"</span>)
      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
      .then(<span class="hljs-function"><span class="hljs-params">users</span> =&gt;</span> {
        <span class="hljs-keyword">const</span> userListElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"user-list"</span>);
        users.forEach(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> {
          <span class="hljs-keyword">const</span> li = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);
          li.innerText = <span class="hljs-string">`Name: <span class="hljs-subst">${user.name}</span>, Age: <span class="hljs-subst">${user.age}</span>, Email: <span class="hljs-subst">${user.email}</span>`</span>;
          userListElement.appendChild(li);
        });
      })
      .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<ul>
<li><p>In the <code>&lt;script&gt;&lt;/script&gt;</code> tag, you call a <code>fetch</code> method that sends a fetch request for data from the controller function called for the <code>users/all</code> route. Remember the controller file used JSON to store and send the request to the view section, this is the view section file now receiving that data with a <code>fetch</code> request.</p>
</li>
<li><p>After receiving the data from the controller, it can render data and User Interface Components to the user.</p>
</li>
</ul>
<h3 id="heading-quick-tips">Quick Tips</h3>
<ul>
<li><p>If you are wondering how the controller back-end function is able to send data it received from model to the view section, know that <code>express</code> works in a way where any function called on a particular route will only store data and send data of that particular route to used in whatever way, in this case, the view section that receives the data via the <code>fetch</code> request.</p>
</li>
<li><p>In MVC, it is advisable to have as many folders, and files that aid the either the Model, View or Controller functions. You can have as many as you want, but it is most important to have a file in the model, view, controller and route folder for every specific function. For example, we had a <code>user</code> route, and corresponding <code>userController.js</code>, <code>UserRoute.js</code>, <code>userBase.js</code> files for it, so if we want to add an <code>admin</code> route, it is design friendly to have corresponding <code>admin</code> controller, routes, model and view files.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Model View Controller (MVC) pattern provides a clear, organized approach to structuring your code, making it easier to maintain, extend, and collaborate on web applications. By separating the concerns of data handling (Model), business logic and control flow (Controller), and presentation (View), MVC allows you to keep your code modular and scalable. Whether you’re building a simple web app or a complex application with multiple contributors, adopting MVC practices ensures that your project remains manageable as it grows. Now that you understand the fundamentals and have seen how to implement MVC in a Node.js application, you can confidently structure your projects to be both efficient and maintainable. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Exploring the CSS :is() and :where() selectors]]></title><description><![CDATA[Knowledge of HTML and CSS. A good grasp of CSS specificity and selectors. CSS has experienced rapid growth over the years, and a noteworthy trend…]]></description><link>https://xylophone.hashnode.dev/exploring-the-css-is-and-where-selectors</link><guid isPermaLink="true">https://xylophone.hashnode.dev/exploring-the-css-is-and-where-selectors</guid><category><![CDATA[CSS]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Sat, 14 Sep 2024 23:00:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ipARHaxETRk/upload/d89da1a8d7d090a0ba777bfe426ef879.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-pre-requisite">Pre-requisite</h2>
<ul>
<li><p>Knowledge of HTML and CSS.</p>
</li>
<li><p>A good grasp of CSS specificity and selectors.</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>CSS has experienced rapid growth over the years, and a noteworthy trend highlighting this evolution is the introduction of new pseudo-classes, enhancing the overall CSS experience. Three particularly notable pseudo-classes that have gained prominence include the <code>:has()</code>, <code>:is()</code>, and <code>:where()</code> pseudo-classes.</p>
<p>A good place to start is Joyce Foster's article on the <code>:has()</code> pseudo-class in a comprehensive article on <a target="_blank" href="https://blog.openreplay.com/how-to-use-the-css-has-selector/">Open Replay</a>, meanwhile our focus is on the remaining two selectors, which share a certain level of correlation.</p>
<p>This article is dedicated to exploring how the <code>:is()</code> pseudo-class facilitates working with multiple selectors, and we'll also investigate the enhancements that the <code>:where()</code> pseudo-class introduces to address common specificity issues. Feel free to dive right into the details.</p>
<h2 id="heading-goals">Goals</h2>
<p>This article caters to both experienced developers seeking to elevate their CSS skills and beginners looking to gain insights into specificity. It offers a firsthand look at how these pseudo-selectors can impact specificity, making it valuable for developers at various skill levels.</p>
<p>Upon reading this article, you can expect to acquire the following insights:</p>
<ul>
<li><p>Develop a clear understanding of how specificity operates.</p>
</li>
<li><p>Recognize the practical utility of the <code>:is()</code> selector.</p>
</li>
<li><p>Learn when to incorporate the <code>:where()</code> selector.</p>
</li>
<li><p>Gain proficiency in using the <code>:where()</code> selector to resolve specificity issues.</p>
</li>
</ul>
<h2 id="heading-brushing-up-on-specificity">Brushing up on Specificity</h2>
<p>To fully grasp the content of this article, it's essential to understand how specificity is applied, as these pseudo-classes exert influence in this regard.</p>
<p>Specificity hinges on four parameters that dictate the weight of a selector, ultimately determining which selectors take precedence in influencing the outcome. The order of priority for these parameters is as follows: importance holds the highest weight, followed by ID, class, and HTML element.</p>
<p>Each parameter within a selector contributes a value of 1. A selector lacking a particular parameter is represented by a value of 0. This representation is formatted as (0,0,0,0) or (1,1,1,1), denoting the presence or absence of importance, ID, class, and HTML element, respectively.</p>
<p>In this context, a selector's specificity is determined by the count of 1s it possesses. For instance, when two selectors vie for the same effect, as illustrated below:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">header</span><span class="hljs-selector-class">.header-class</span> {
  <span class="hljs-comment">/**Some CSS**/</span>
}

<span class="hljs-selector-tag">header</span><span class="hljs-selector-id">#header</span> {
  <span class="hljs-comment">/**Some CSS**/</span>
}
</code></pre>
<ul>
<li><p>The first selector possesses a specificity rating of (0,0,1,1) as it includes both element and class selectors. The rating follows the order of importance, ID, class, and element, denoted as (important keyword, id, class, element).</p>
</li>
<li><p>The second selector holds a specificity rating of (0,1,0,1). Without an <code>!important</code> declaration and with a 1 in the second parameter, it attains a higher specificity.</p>
</li>
</ul>
<p>This provides a high-level overview of how specificity is applied. The <code>:is()</code> and <code>:where()</code> pseudo-classes can either influence specificity to achieve specific effects (pun intended) or not. For a practical guide on understanding the concept of specificity, refer to W3Schools' excellent resource on <a target="_blank" href="https://www.w3schools.com/css/css_specificity.asp">specificity</a>.</p>
<p>With this understanding, let's explore scenarios where these selectors prove useful. As we delve further, we'll encounter instances where both selectors impact specificity.</p>
<h2 id="heading-ignoring-errors-with-is">Ignoring errors with :is()</h2>
<p>When chaining selectors together, it's common to encounter mistakes with invalid selectors. Consider the HTML snippet below:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flow"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>:is<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> pseudo-class<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    A <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"highlight"</span>&gt;</span>super useful<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span> pseudo-class for writing less
    CSS
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">""</span>&gt;</span>Read more about it here<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>, or
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>watch this video<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> where I take a look at it.
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>learn more<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
</code></pre>
<ul>
<li><p>This snippet features a <code>header</code> element containing <code>p</code>, <code>h1</code>, and <code>a</code> elements.</p>
</li>
<li><p>Now, let's attempt to style the various elements using CSS.</p>
</li>
</ul>
<pre><code class="lang-css"><span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">h1</span>,
<span class="hljs-selector-tag">header</span> <span class="hljs-selector-pseudo">:a</span> {
  <span class="hljs-attribute">color</span>: olivedrab;
}
</code></pre>
<ul>
<li><p>While chaining the selectors above, it's crucial to observe a mistake in the second selector, <code>header :a</code>.</p>
</li>
<li><p>This error renders the CSS invalid, resulting in the inability to apply the color change to the <code>header</code> and <code>a</code> HTML elements, as depicted in the image below:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724414742406/de727dc2-e14b-42bc-be4a-c9bfd6cc2e4b.gif" alt class="image--center mx-auto" /></p>
<p>Imagine making a mistake as minor as this and struggling to debug hundreds of lines of CSS due to the challenge of spotting such errors. This is precisely where the <code>:is()</code> pseudo-class becomes invaluable.</p>
<p>Styling the same HTML with the <code>:is()</code> pseudo-class enables us to better overlook these errors. Here's how to implement it:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">header</span> <span class="hljs-selector-pseudo">:is(h1</span>, <span class="hljs-selector-pseudo">:a)</span> {
  <span class="hljs-attribute">color</span>: olivedrab;
}
</code></pre>
<ul>
<li><p>The <code>:is()</code> syntax essentially poses a question: Are the descendant or combined selectors related? In the provided CSS, it asks whether <code>h1</code> and <code>:a</code> are descendants of <code>header</code>. This is the inquiry the browser undertakes when parsing the <code>:is()</code> pseudo-class.</p>
</li>
<li><p>Returning to our example, we've modified the previous CSS to incorporate the <code>:is()</code> keyword. This adjustment prompts the browser to check if <code>h1</code> and <code>:a</code> are descendants of <code>header</code> and then applies the new color styling to the valid descendant.</p>
</li>
<li><p>Observe in the image below the outcome of this change: the <code>olivedrab</code> color is applied to the <code>h1</code> element, while no change occurs on the <code>:a</code> selector because of the typing error.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724414857109/28b49912-e6f3-4166-b00c-b82a435eb433.gif" alt class="image--center mx-auto" /></p>
<p>This proves beneficial when dealing with extensive CSS codebases. Using <code>:is()</code> allows you to identify elements that are not correctly applied and investigate those specific instances. This approach contrasts with situations where nothing works at all, providing a more manageable debugging process for large CSS projects.</p>
<h2 id="heading-refactoring-with-is">Refactoring with :is()</h2>
<p>A small yet significant advantage offered by the <code>:is()</code> selector is its ability to combine selectors without unnecessary repetition, adhering to the principle of refactoring: DON'T REPEAT YOURSELF (DRY). Here are scenarios where this capability can prove helpful.</p>
<p>Let's begin with a card HTML sample to illustrate this:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"title"</span>&gt;</span>Title goes here<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor, <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>sit amet consectetur<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> adipisicing elit.
      Aliquid sapiente perferendis nulla sed consequuntur eveniet. Itaque
      veritatis qui labore quia odio nihil, magni soluta facilis necessitatibus
      cumque repellendus optio laborum.
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>I'm causing problems<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, ad!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<ul>
<li>The provided snippet is for a demonstration of a card element. Please take note of the arrangement of the class and id selectors.</li>
</ul>
<p>Now, let's implement default styling to enhance the visual appearance of the HTML:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-built_in">var</span>(--ff-primary);
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.125em</span>;
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">1.6</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--clr-body);
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">var</span>(--clr-bg);
}

<span class="hljs-selector-class">.card</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">3em</span>;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">3em</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.15</span>);
  <span class="hljs-attribute">background</span>: white;
}

<span class="hljs-selector-class">.title</span> {
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">900</span>;
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">0.8</span>;
}

<span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-built_in">min</span>(<span class="hljs-number">90%</span>, <span class="hljs-number">62.5rem</span>);
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
}
</code></pre>
<ul>
<li><p>The CSS snippet above provides styling to our HTML.</p>
</li>
<li><p>Observe in the image below the font appearance and color of all the elements, as these are the aspects that will be altered:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724416497288/22cb337e-766f-4b1d-8094-e33789ddc333.gif" alt class="image--center mx-auto" /></p>
<p>If, for any reason, we wish to combine selectors to modify the font appearance and colors of both elements and classes, we can augment the existing CSS as follows:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.card</span> <span class="hljs-selector-class">.title</span>,
<span class="hljs-selector-class">.card</span> <span class="hljs-selector-tag">h3</span>,
<span class="hljs-selector-class">.card</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Trebuchet MS"</span>, <span class="hljs-string">"Lucida Sans Unicode"</span>, <span class="hljs-string">"Lucida Grande"</span>,
    <span class="hljs-string">"Lucida Sans"</span>, Arial, sans-serif;
}
</code></pre>
<ul>
<li><p>The additions above modify the font style of our selectors.</p>
</li>
<li><p>Observe the transition from the default font to the new font in the image below:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724416551253/e308110c-6301-401f-8966-c29bd700e1f6.gif" alt class="image--center mx-auto" /></p>
<p>However, what if we intended to combine additional selectors? Must we repetitively type out <code>.card</code> each time? Such redundancy could lead to bloated CSS code. Fortunately, with the <code>:is()</code> selector, we can effortlessly achieve the same effect while minimizing repetition.</p>
<p>Here's how you can attain the same font change using the <code>:is()</code> selector:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.card</span> <span class="hljs-selector-pseudo">:is(.title</span>, <span class="hljs-selector-tag">h3</span>, <span class="hljs-selector-tag">p</span>) {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Trebuchet MS"</span>, <span class="hljs-string">"Lucida Sans Unicode"</span>, <span class="hljs-string">"Lucida Grande"</span>,
    <span class="hljs-string">"Lucida Sans"</span>, Arial, sans-serif;
}
</code></pre>
<ul>
<li><p>In the CSS code above, we employed the <code>:is()</code> selector to verify whether the descendant selectors are genuinely descendants of the <code>.card</code> class. Consequently, there is no need to redundantly type out <code>.card</code> to combine selectors, as was done previously.</p>
</li>
<li><p>Observe in the image below that the font remains consistent, and we achieve the same effect:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724416571815/fa86edc0-3571-40e0-a3d6-2dd846174c92.gif" alt class="image--center mx-auto" /></p>
<p>Another clever application of refactoring CSS with <code>:is()</code> is styling a descendant selector that belongs to two or more higher selectors. Let's examine some code to illustrate this.</p>
<p>Consider the new additions to our HTML:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header-title"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome to Open Replay<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"title"</span>&gt;</span>Title goes here<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor, <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>sit amet consectetur<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> adipisicing elit.
      Aliquid sapiente perferendis nulla sed consequuntur eveniet. Itaque
      veritatis qui labore quia odio nihil, magni soluta facilis necessitatibus
      cumque repellendus optio laborum.
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>I'm causing problems<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, ad!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<ul>
<li>In the HTML code above, the layout for a card remains the same, but a <code>header</code> element containing a <code>p</code> element has been added.</li>
</ul>
<p>If, for any reason, you wish to style the <code>p</code> element within both the <code>header</code> element and the <code>.card</code> <code>div</code>, you can achieve this with the <code>:is()</code> selector, simplifying the process without unnecessary repetition. Here's how you would implement it:</p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:is(.card</span>, <span class="hljs-selector-tag">header</span>) <span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">color</span>: brown;
}
</code></pre>
<ul>
<li><p>In the CSS above, the browser is instructed to apply the hover effect to any <code>p</code> element within a <code>.card</code> selector and a <code>header</code> element, eliminating the need to redeclare <code>p:hover</code> for each element.</p>
</li>
<li><p>The outcome is evident as all <code>p</code> selectors turn brown upon hovering.</p>
</li>
<li><p>Observe the color change below as the cursor hovers over the <code>p</code> elements:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724416622757/60ca98a6-98e0-471e-9130-0a7ac5055acc.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-the-problem-with-is">The problem with :is()</h2>
<p>While the <code>:is()</code> pseudo-class proves valuable for simplifying selectors and cleaning up code, it comes with a specificity concern. In the upcoming paragraphs, we will explore how the <code>:where()</code> selector, closely related to <code>:is()</code>, addresses specificity and examine a scenario where it can be effectively utilized.</p>
<p>For instance, consider the code snippets below.</p>
<p>The HTML markup is nearly identical to what we've been using, but with subtle changes:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>:is<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> pseudo-class<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    A <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"highlight"</span>&gt;</span>super useful<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span> pseudo-class for writing less
    CSS
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Read more about it here, or watch this video where I take a look at it.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>learn more<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
</code></pre>
<p>Here's where CSS becomes intriguing:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">header</span> <span class="hljs-selector-pseudo">:is(h1</span>, <span class="hljs-selector-tag">a</span>, <span class="hljs-selector-class">.highlight</span>) {
  <span class="hljs-attribute">color</span>: green;
}

<span class="hljs-selector-class">.btn</span> {
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.5em</span> <span class="hljs-number">1em</span>;
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#234</span>;
  <span class="hljs-attribute">color</span>: white;
}
</code></pre>
<ul>
<li><p>The <code>:is()</code> selector, as expected, verifies whether the <code>h1</code>, <code>a</code>, and <code>.highlight</code> selectors are descendants of the <code>header</code> selector.</p>
</li>
<li><p>Since all descendant selectors satisfy the conditions of the <code>:is()</code> selector, all the colors change to <code>green</code>.</p>
</li>
<li><p>Notably, the <code>btn</code> class has the color <code>white</code> and should have higher specificity, ideally being applied. In other words, the button with the text "learn more" should appear with a <code>white</code> color.</p>
</li>
<li><p>However, observe in the image below that the button displays as <code>green</code> instead of <code>white</code>:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724416675052/d9bf5cbe-193f-426c-b185-46acb331a17f.gif" alt class="image--center mx-auto" /></p>
<p>The problem lies in the application of the <code>:is()</code> pseudo-class in the <code>header :is(h1, a, .highlight)</code> selector. While it effectively groups multiple selectors together to apply a common set of styles, it doesn't impact the specificity of the individual selectors within the group.</p>
<p>In the provided code, the <code>:is(h1, a, .highlight)</code> section matches any <code>h1</code> element, any <code>a</code> element, and any element with the class <code>.highlight</code> that is a descendant of the <code>header</code> element. The <code>color: green;</code> rule is then applied to these matched elements.</p>
<p>Now, when it comes to the <code>.btn</code> selector, it doesn't possess the same specificity as the <code>:is(h1, a, .highlight)</code> selector, but it is still affected by it since it is a descendant of the <code>header</code> element.</p>
<p>Following CSS cascade and specificity rules, the <code>color: green;</code> rule from the <code>header :is(h1, a, .highlight)</code> selector takes precedence over the <code>color: white;</code> rule in the <code>.btn</code> selector.</p>
<p>To address this issue, we can either enhance the specificity of the <code>.btn</code> selector or make it more specific than the <code>header :is(h1, a, .highlight)</code> selector. Alternatively, we can employ the <code>:where()</code> selector, which we'll explore in the next section as a more straightforward solution.</p>
<h2 id="heading-using-where">Using :where()</h2>
<p>To resolve the specificity issue highlighted in the previous section, let's implement the following changes to the CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">header</span> <span class="hljs-selector-pseudo">:where(h1</span>, <span class="hljs-selector-tag">a</span>, <span class="hljs-selector-class">.highlight</span>) {
  <span class="hljs-attribute">color</span>: green;
}

<span class="hljs-selector-class">.btn</span> {
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.5em</span> <span class="hljs-number">1em</span>;
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#234</span>;
  <span class="hljs-attribute">color</span>: white;
}
</code></pre>
<ul>
<li><p>In the code above, the sole modification made is substituting the <code>:where()</code> selector for the <code>:is()</code> selector.</p>
</li>
<li><p>This alteration achieves the desired effect, and the color of the "learn more" button reverts to white. Observe the color change in the button class below, thereby providing higher specificity to the <code>:where()</code> selector:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724416732180/1c68519e-a4a3-4e3d-b894-c58cb8883c89.gif" alt class="image--center mx-auto" /></p>
<p>The issue is resolved by replacing the <code>:is()</code> pseudo-class with <code>:where()</code>. Although these pseudo-classes share similarities, a crucial distinction lies in how they affect specificity.</p>
<p>The <code>:where()</code> pseudo-class is a functional pseudo-class that accepts a selector list, behaving similarly to <code>:is()</code>. However, unlike <code>:is()</code>, <code>:where()</code> doesn't impact specificity. It functions to allow a selector list to be used without altering the specificity of the entire selector.</p>
<p>When using <code>header {:where(h1, a, .highlight)}</code>, the styles apply to any <code>h1</code> element, any <code>a</code> element, and any element with the class <code>.highlight</code> that is a descendant of the <code>header</code> element. Importantly, the specificity of the <code>:where()</code> selector doesn't interfere with the specificity of the subsequent <code>.btn</code> selector. The specificity remains unchanged, akin to writing the selector without <code>:where()</code>.</p>
<p>This feature enables grouping selectors without modifying specificity. Consequently, the <code>color: white;</code> rule in the <code>.btn</code> selector is not overridden by the <code>color: green;</code> rule in <code>:where(h1, a, .highlight)</code>. As a result, the text inside elements with the class <code>.btn</code> now appears in white, as intended.</p>
<h3 id="heading-specificity-battles">Specificity battles</h3>
<p>If the <code>:where()</code> selector negates specificity, it can prove valuable in specific scenarios, such as when establishing default values and configuring CSS for easy overrides. Let's explore an example with a card demo:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card flow"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"title"</span>&gt;</span>Article Topic<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor, <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>sit amet consectetur<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> adipisicing elit.
      Aliquid sapiente perferendis nulla sed consequuntur eveniet. Itaque
      veritatis qui labore quia odio nihil, magni soluta facilis necessitatibus
      cumque repellendus optio laborum.
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Foreword by Federico<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque, ad!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<ul>
<li>The provided HTML setup is straightforward, featuring a card that nearly spans the width of the web page. Pay attention to the <code>flow</code> class, as we will analyze specificity changes originating from there.</li>
</ul>
<p>Now, let's examine the styling for the card:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* Other Styling */</span>

<span class="hljs-selector-class">.flow</span> &gt; *<span class="hljs-selector-pseudo">:not(</span><span class="hljs-selector-pseudo">:first-child)</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">1em</span>;
}

<span class="hljs-selector-class">.card</span> &gt; <span class="hljs-selector-tag">h3</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20em</span>;
}
</code></pre>
<ul>
<li><p>The preceding styling is conventional and doesn't impact the discussion of our example.</p>
</li>
<li><p>The <code>.flow &gt; *:not(:first-child)</code> selector targets all direct children of elements with the class <code>.flow</code>, excluding the first child. The rule applied involves adding a top margin, with the value derived from the custom property <code>--flow-space</code>, and a fallback value of <code>1em</code> if <code>--flow-space</code> is not set.</p>
</li>
<li><p>The <code>h3</code> selector targets all <code>h3</code> elements, setting a fixed top margin of <code>20em</code>.</p>
</li>
</ul>
<p>However, the top margin rule remains unchanged. Why? This is due to the fact that the specificity of the <code>.flow</code> selector code has elevated, leading to a conflict in determining which rules should be applied, resulting in specificity issues.</p>
<p>Observe in the image below that the <code>margin-top: 20em</code> is not being applied, and there is no space between the text, even though space is expected:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724416779413/1ac21ebe-fbd6-4d17-8937-d1a0c590497e.gif" alt class="image--center mx-auto" /></p>
<p>However, by employing the <code>:where()</code> selector, the margin is correctly applied. Let's see how to implement this with CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flow</span> &gt; <span class="hljs-selector-pseudo">:where(</span><span class="hljs-selector-pseudo">:not(</span><span class="hljs-selector-pseudo">:first-child))</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">0.5em</span>;
}

<span class="hljs-selector-class">.card</span> &gt; <span class="hljs-selector-tag">h3</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20em</span>;
}
</code></pre>
<ul>
<li>The alterations made above involve the introduction of the <code>:where()</code> selector. Observe in the image below that the <code>margin-top</code> rule is appropriately applied, and the desired space is present:</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724416824873/fb504113-e938-4541-8d2b-c328b21d5bd6.gif" alt class="image--center mx-auto" /></p>
<p>In the initial snippet of this section, the <code>:not(:first-child)</code> pseudo-class is employed, selecting all elements that are not the first child of their parent element. However, the <code>:not(:first-child)</code> pseudo-class carries higher specificity than the <code>.card &gt; h3</code> selector. Consequently, the <code>margin-top</code> value specified for <code>.card &gt; h3</code> is overridden by the more specific selector.</p>
<p>Conversely, in the second code snippet, the <code>:where()</code> pseudo-class is utilized, which differs slightly. The <code>:where()</code> pseudo-class doesn't impact specificity; it serves as a wrapper allowing you to group selectors without altering specificity. As a result, the specificity of <code>.card &gt; h3</code> is not overridden, and the <code>margin-top</code> value is applied.</p>
<p>While this scenario may seem complex, it serves as a clear example where using the <code>:where()</code> pseudo-class can help avoid prolonged debugging sessions caused by specificity conflicts.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The exploration of the CSS <code>:is()</code> and <code>:where()</code> selectors in this article has shed light on tools that enhance the efficiency and maintainability of stylesheets.</p>
<p>These pseudo-classes, while similar in their ability to group selectors, differ significantly in terms of specificity.</p>
<p>The <code>:is()</code> selector proves to be a valuable asset for simplifying selectors, ignoring errors, and refactoring code.</p>
<p>It excels in scenarios where developers want to apply styles to multiple selectors within a group. However, its impact on specificity can lead to unexpected outcomes.</p>
<p>On the other hand, the <code>:where()</code> selector emerges as a solution to specificity challenges. By allowing the grouping of selectors without altering specificity, it proves beneficial in scenarios where maintaining specificity is crucial, as seen in the specificity battles and the avoidance of margin issues in the final example.</p>
<p>Both pseudo-classes cater to developers seeking cleaner, more concise code, but careful consideration of their specificity implications is essential.</p>
<p>Whether it's handling errors, refactoring code, or managing specificity battles, understanding when to use <code>:is()</code> or <code>:where()</code> empowers developers to create more robust and maintainable stylesheets.</p>
<h2 id="heading-resources-to-read-more">Resources to read more</h2>
<ul>
<li><a target="_blank" href="https://www.w3schools.com/css/css_specificity.asp">A complete guide to CSS specificity</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Union Of Scripts]]></title><description><![CDATA[Understanding Unions In Typescript]]></description><link>https://xylophone.hashnode.dev/union-of-scripts</link><guid isPermaLink="true">https://xylophone.hashnode.dev/union-of-scripts</guid><category><![CDATA[webdev]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[frontend]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Sat, 03 Aug 2024 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722853109953/a3f3546e-344d-491f-9c93-5c24a28a9263.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>cover photo credit: Ismail Aghazada</em></p>
<h2 id="heading-introduction">Introduction</h2>
<p>To ensure that you understand how to use every TS feature discussed in this series, it is important I keep all articles lazer-focused on the issue of discussion, and it may result in the articles being too short or too long, or just right. For today, I will explore the Union type feature and its intricasies.</p>
<h2 id="heading-union-of-what">Union of What?</h2>
<p>Union is a data type that allows you specify that a model can have two or more combinations of types. Union makes this possible with a pipe <code>|</code> sign syntax, like below:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span>  score: <span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span>  = <span class="hljs-number">33</span>

score = <span class="hljs-number">44</span>

score = <span class="hljs-literal">true</span> <span class="hljs-comment">// throws in an error</span>
</code></pre>
<ul>
<li><code>score</code> can be a number or a string, but if a boolean data type is referenced to it, it will throw an error</li>
</ul>
<p>The Union type can also be used to combine type aliases alongside data types:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
    name: <span class="hljs-built_in">string</span>;
    id: <span class="hljs-built_in">number</span>
}

<span class="hljs-keyword">type</span> Admin = {
    username: <span class="hljs-built_in">string</span>; 
    id: <span class="hljs-built_in">number</span>
}

<span class="hljs-keyword">let</span> FirstUser: User | Admin = {
    name : <span class="hljs-string">"Kelvin"</span>,
    id : <span class="hljs-number">763</span>
}
</code></pre>
<ul>
<li><p><code>FirstUser</code> uses the union data type to combine <code>User</code> and <code>Admin</code> data types.</p>
</li>
<li><p>If any type is added to <code>FirstUser</code> without being specified in any of the earlier type aliases, <code>User</code> and <code>Admin</code>, Typescript(TS) static checking throws in an error.</p>
</li>
</ul>
<h2 id="heading-union-functions">Union Functions</h2>
<p>Most times when working with large code bases, correctly describing what the function can take in as a parameter, or what it can return can prevent life-threatening bugs from popping up in your code base.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserID</span>(<span class="hljs-params">id : <span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${id}</span> is this, and so here is your Reg no:...`</span>)
}
</code></pre>
<ul>
<li><code>getUserID</code> function has an <code>id</code> parameter that could either be a string or a number.</li>
</ul>
<p>Using Union types in our functions also presents a minimal issue.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserID</span> (<span class="hljs-params">id : <span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${id}</span> is this, and so here is your Reg no:...`</span>)
    id.toLowerCase() <span class="hljs-comment">// Triggers an error</span>
}
</code></pre>
<ul>
<li><p><code>getUserID</code> takes in an <code>id</code> parameter that can either be a string or a number, but how come calling <code>id.toLowerCase</code> returns an error?</p>
</li>
<li><p>This is because the <code>id</code> parameter can be a string, and then be changed to a number later on in the function. Hence, calling a string method on <code>id</code> is correct if <code>id</code> is a string, but due to the fact that <code>id</code> can later become a number will definitely lead to errors, since string methods cannot work on numbers.</p>
</li>
<li><p>The solution here is to specify the methods on these functions using conditionals:</p>
</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserID</span> (<span class="hljs-params">id : <span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${id}</span> is this, and so here is your Reg no:...`</span>)
    <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> id === <span class="hljs-string">"string"</span>){
        id.toLowerCase()
    }
}
</code></pre>
<h2 id="heading-unions-in-arrays">Unions in arrays</h2>
<p>This is how to specify the content of arrays:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> type1 : <span class="hljs-built_in">string</span>[] = [<span class="hljs-string">"su"</span>,<span class="hljs-string">"siuu"</span>,<span class="hljs-string">"siuuu"</span>]
<span class="hljs-keyword">const</span> type2 : <span class="hljs-built_in">number</span>[] = [<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
<span class="hljs-keyword">const</span> type3 : <span class="hljs-built_in">string</span>[] | <span class="hljs-built_in">number</span>[] = [<span class="hljs-string">"fdsa"</span>,<span class="hljs-string">"lfdha"</span>,<span class="hljs-number">4</span>] <span class="hljs-comment">// error</span>
<span class="hljs-keyword">const</span> type4 : (<span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>)[] = [<span class="hljs-string">"fdsa"</span>,<span class="hljs-string">"lfdha"</span>,<span class="hljs-number">4</span>] <span class="hljs-comment">// correct</span>
</code></pre>
<ul>
<li><p><code>type1</code> and <code>type2</code> are the normal ways of describing arrays that should have one data type of content.</p>
</li>
<li><p>To use the union data type for arrays, you may try to combine both <code>string[]</code> and <code>number[]</code> data types together, but this only directs the code that all the array contents in <code>type3</code> should either be all strings or all numbers but cannot be mixed. *<code>type4</code> is the way to correctly enable an array have any type of content with different data types in it at an instance.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding and correctly implementing TypeScript's Union types is crucial for creating robust and error-free code. The Union type allows for flexible data type combinations, enhancing the adaptability of your models and functions. However, careful consideration is required to avoid common pitfalls, such as method mismatches when handling mixed types. By leveraging Union types effectively, you can write more versatile and safer code, especially in complex projects with varying data requirements.</p>
]]></content:encoded></item><item><title><![CDATA[Typescript Arrays]]></title><description><![CDATA[A Beginner's Preview]]></description><link>https://xylophone.hashnode.dev/typescript-arrays</link><guid isPermaLink="true">https://xylophone.hashnode.dev/typescript-arrays</guid><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Mon, 29 Jul 2024 08:00:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722239352584/e8ea9d19-023e-4973-b5c1-54209d2f5a03.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Cover photo credit:</em> <a target="_blank" href="https://javascript.plainenglish.io/a-guide-to-typescript-array-type-bfdf59d8c516"><em>An article by Johnny Simpson</em></a></p>
<h2 id="heading-introduction">Introduction</h2>
<p>Arrays in Typescript don't have much attached to them, but behind the scenes there is more to their working than how arrays function in Javascript. In this article, you'll learn about the complexities and benefits TS brings to the workings of arrays.</p>
<h2 id="heading-array-types">Array Types</h2>
<p>Besides specifying an array in TS, we can also specify the content that arrays can have, but first, observe a strange behavior of arrays in TS. If an array is declared like :</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> houses = [];
houses.push(<span class="hljs-string">"bungalow"</span>)
</code></pre>
<ul>
<li><code>houses</code> implicitly carries a data type, <code>never</code>, and cannot carry out array methods like <code>push</code> . <code>never</code> implies that the data type should never be mutated, and this will lead to an error.</li>
</ul>
<p>To stop this, simply specify the array like the second line, because specifying an array like the first line implies that the array should always be empty and will induce static checking errors.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> houses: [] = []; 
<span class="hljs-keyword">const</span> superHouses: <span class="hljs-built_in">string</span>[] = []; 
<span class="hljs-keyword">const</span> superHousesAndLevels : <span class="hljs-built_in">string</span>[] &amp; <span class="hljs-built_in">number</span>[] = []

superHouses.push(<span class="hljs-string">"Cave Glass Houses"</span>);
superHousesAndLevels.push(<span class="hljs-string">"etch skyscrappers"</span>)
superHousesAndLevels.push(<span class="hljs-number">45</span>)
</code></pre>
<ul>
<li><p>The <code>houses</code> declaration still imply the never type.</p>
</li>
<li><p><code>superHouses</code> on the other hand implies the type of contents the array should have;</p>
</li>
<li><p><code>superHousesAndLevels</code> allows for the contents of the array to be both strings and numbers. With as many parameter data types as you want.</p>
</li>
</ul>
<p>You can also specify that an array should have only arrays inside it:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> Coordinates : <span class="hljs-built_in">number</span>[][] = [
    [<span class="hljs-number">638</span>,<span class="hljs-number">7834</span>]
]
</code></pre>
<ul>
<li><code>Coordinates</code> should only have an array that has arrays with numbers inside.</li>
</ul>
<h2 id="heading-array-aliases">Array Aliases</h2>
<p>In the same way, type aliases can be used for variables, is the same way it can be used in arrays.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
    name : <span class="hljs-built_in">string</span>;
    isActive : <span class="hljs-built_in">boolean</span>; 
}

<span class="hljs-keyword">const</span> allUsers : User[] = []

allUsers.push({name: <span class="hljs-string">""</span>, isActive: <span class="hljs-literal">true</span>});
</code></pre>
<ul>
<li><p>a <code>User</code> alias is declared, with two parameters.</p>
</li>
<li><p><code>allUsers</code> is defined with the <code>User</code> alias, and parameters are typed with <code>User</code> guidelines.</p>
</li>
</ul>
<h2 id="heading-readonly-arrays">Readonly Arrays</h2>
<p>The <code>ReadonlyArray</code> is a special TS type that describes arrays that should not be changed:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> immutableArray : ReadonlyArray&lt;<span class="hljs-built_in">String</span>&gt; = [
    <span class="hljs-string">"shakan"</span>,<span class="hljs-string">"awa"</span>,<span class="hljs-string">"sheikunude"</span>
]

immutableArray.push(<span class="hljs-string">"yyy"</span>) <span class="hljs-comment">// static error</span>
</code></pre>
<ul>
<li>The <code>immutableArray</code> is described to be unchangeable in parts of the code,and when we call a method to update the array, TS static checking signals an error.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Obviously, this is not all to arrays, but should get you started with using arrays to ensure clean code and type safety in your code bases.</p>
]]></content:encoded></item><item><title><![CDATA[Playing With Objects]]></title><description><![CDATA[A Typescript Approach]]></description><link>https://xylophone.hashnode.dev/playing-with-objects</link><guid isPermaLink="true">https://xylophone.hashnode.dev/playing-with-objects</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[frontend]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Sun, 21 Jul 2024 19:52:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721590942285/9a7dac95-eca5-4d5f-a63d-0bbf195bfdf4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong><em>Cover photo credit:</em></strong> <a target="_blank" href="https://www.linkedin.com/pulse/typescript-object-types-interface-class-enum-array-tuple-hassan-fathy-xniyf"><strong><em>An Article by Hassan Fatthy</em></strong></a></p>
<h2 id="heading-introduction">Introduction</h2>
<p>Typescript(TS) is definitely good, but is not entirely the elixir to JavaScript(JS) perfection. There are still some odd behaviors in TS, especially when dealing with objects. Sit tight as I unravel TS behavior when it comes to objects.</p>
<h2 id="heading-objects-in-ts">Objects In TS</h2>
<p>Objects are data structures primarily used for capturing key-value pairs. For instance, if you want to send an instance to a database, you can group the data in fields using a <code>key : "name"</code>, and the <code>values: "Kelvin", "Okuroemi"</code>. Here's one:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> infoAboutMe ={
    name: <span class="hljs-string">"Kelvin"</span>,
    age: <span class="hljs-number">21</span>,
    hasJob: <span class="hljs-literal">false</span>,
    hireMe: <span class="hljs-literal">true</span>
}
</code></pre>
<p>Most times, the reason TS is used when working with objects is to specify the inputs of object fields as they are used in a function:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">submitResume</span>(<span class="hljs-params">{name:<span class="hljs-built_in">string</span>, hasJob: <span class="hljs-built_in">boolean</span>}</span>)</span>{
<span class="hljs-comment">// Some code ...</span>
}
</code></pre>
<p>As a result, calling the <code>submitResume()</code> function without an object parameter will trigger static checking. (submitResumeError.png)[] To stop this, we have to specify the parameters,</p>
<pre><code class="lang-typescript">submitResume({name: <span class="hljs-string">"Kelvin"</span>, hasJob: <span class="hljs-literal">false</span>})
</code></pre>
<p>Now if you wanted to specify that an object should have to return an object, you could do it by:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">submitResume</span>(<span class="hljs-params">{name:<span class="hljs-built_in">string</span>, hasJob: <span class="hljs-built_in">boolean</span>}</span>):</span>{isQualified: <span class="hljs-built_in">boolean</span>}{
<span class="hljs-comment">// Some code ...</span>
<span class="hljs-keyword">return</span> {isQualified:<span class="hljs-literal">true</span>}
}
</code></pre>
<ul>
<li>Notice the output declaration syntax <code>:{isQualified:boolean}</code> that warrants the <code>submitResume</code> function to return an a boolean in the form of an object.</li>
</ul>
<h2 id="heading-oddish">Oddish</h2>
<p>There are some behaviors in TS which might be able to evade TS static checking, for example:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup</span>(<span class="hljs-params">{name:<span class="hljs-built_in">string</span>}</span>)</span>{
<span class="hljs-comment">//  Some code...</span>
}
<span class="hljs-keyword">let</span> details = {name:<span class="hljs-string">"SideSchool"</span>, rateIdea: <span class="hljs-number">9.4</span>}
createStartup(details)
</code></pre>
<ul>
<li><p><code>createStartup</code> function specifies only a <code>name:string</code> parameter.</p>
</li>
<li><p><code>details</code> contains an extra field <code>rateIdea:9.4</code> and is passed on to <code>createStartup</code></p>
</li>
<li><p>However this does not trigger static checking which is odd, considering the fact that we specified for only one parameter.</p>
</li>
</ul>
<p>To avoid errors like this, we use <strong>Type Aliases</strong>.</p>
<h2 id="heading-type-aliases">Type Aliases</h2>
<p>In the section prior to this, we tried to use a variable details to specify a range of values, and it bypassed our TS static checking character. If we want to specify a range of types and still keep static checking in place, we use type aliases.</p>
<p>Type aliases help us specify a range of types to be used beforehand, and will flag errors if further components neglect the alias. Using our <code>createStartup</code> function from above:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Startup = {
  name: <span class="hljs-built_in">string</span>;
  niche: <span class="hljs-built_in">string</span>;
  rateIdea: <span class="hljs-built_in">number</span>;
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup</span>(<span class="hljs-params">startup: Startup</span>): <span class="hljs-title">Startup</span> </span>{
  <span class="hljs-comment">//  Some code...</span>
  <span class="hljs-keyword">return</span> name: {<span class="hljs-string">"SideSchool"</span>,niche:<span class="hljs-string">"EdTech"</span>, rateIdea: <span class="hljs-number">9.4</span>};
}

createStartup({ name: <span class="hljs-string">"SideSchool"</span>, niche: <span class="hljs-string">"EdTech"</span>, rateIdea: <span class="hljs-number">9.4</span> });
</code></pre>
<ul>
<li><p>First of all we create a type alias <code>Startup</code> with the keyword <code>type</code></p>
</li>
<li><p>Then we write that the <code>createStartup</code> function's parameter should have all the types already specified in the <code>Startup</code> type alias. It should also return a value with <code>Startup</code> type aliases.</p>
</li>
<li><p>After that you call the function with the appropriate parameters and corresponding types as specified in the <code>Startup</code> type alias.</p>
</li>
<li><p>In this case, type aliases replace the use of the variable <code>details</code> for specifying a range of types and will trigger static checking if need be.</p>
</li>
</ul>
<p>Another reason we might use the type aliases is to prevent scenarios where we have to define the same range of types for different function.</p>
<p><strong><em>No alias:</em></strong></p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup1</span>(<span class="hljs-params">{ name: <span class="hljs-built_in">string</span>, cost: <span class="hljs-built_in">number</span> }</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup2</span>(<span class="hljs-params">{ name: <span class="hljs-built_in">string</span>, cost: <span class="hljs-built_in">number</span> }</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup3</span>(<span class="hljs-params">{ name: <span class="hljs-built_in">string</span>, cost: <span class="hljs-built_in">number</span> }</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}
</code></pre>
<p><strong><em>With aliases:</em></strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> StartupDetails = {
    name: <span class="hljs-built_in">string</span>,
    cost: <span class="hljs-built_in">number</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup1</span>(<span class="hljs-params">details: StartupDetails</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup2</span>(<span class="hljs-params">details: StartupDetails</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup3</span>(<span class="hljs-params">details: StartupDetails</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}
</code></pre>
<p>To cap it, we can also define type aliases to accommodate unions(a choice between two or more types).</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Union = <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span> | <span class="hljs-built_in">boolean</span>;

<span class="hljs-keyword">const</span> unionVar0: Union = <span class="hljs-string">"union"</span>;
<span class="hljs-keyword">const</span> unionVar1: Union = <span class="hljs-number">46</span>;
<span class="hljs-keyword">const</span> unionVar2: Union = <span class="hljs-literal">false</span>;
</code></pre>
<ul>
<li><p>We specify a <code>Union</code> type alias with three choice of types.</p>
</li>
<li><p>Then define all variables to have the type of <code>Union</code>, this can allow any variable to have any type already specified in <code>Union</code> type alias without triggering static checking.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In wrapping up our exploration of TypeScript’s handling of objects, it’s clear that while TypeScript offers powerful tools for enhancing JavaScript’s type safety, it also comes with its quirks.</p>
<p>We’ve seen how TypeScript's static checking can sometimes be bypassed with certain object structures and how type aliases can help maintain stricter control over the types in our code.</p>
<p>By leveraging type aliases, you not only enforce consistent type definitions across your functions but also streamline your codebase, reducing redundancy and minimizing potential errors. This practice of using type aliases can be particularly valuable when dealing with complex data structures or multiple functions requiring similar type definitions.</p>
<p>In conclusion, mastering TypeScript’s type system, especially with the use of type aliases, can greatly enhance code reliability and readability. While TypeScript might not be a flawless solution, understanding its nuances and leveraging its features effectively can lead to more robust and maintainable code. So, as you continue to refine your TypeScript skills, keep these insights in mind to ensure your code is both efficient and error-resistant.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering the Art of Objects]]></title><description><![CDATA[A TypeScript Journey]]></description><link>https://xylophone.hashnode.dev/mastering-the-art-of-objects</link><guid isPermaLink="true">https://xylophone.hashnode.dev/mastering-the-art-of-objects</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[coding]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Tue, 16 May 2023 13:20:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684222227763/f073a1d9-fee0-4c75-8bac-319d06782c40.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong><em>Cover photo credit:</em></strong> <a target="_blank" href="https://www.ceos3c.com/"><strong><em>https://www.ceos3c.com/</em></strong></a></p>
<h2 id="heading-introduction">Introduction</h2>
<p>Typescript (TS) is good but is not entirely the elixir to Javascript(JS) perfection. There are still some odd behaviors in TS, especially when dealing with objects. Sit tight as I unravel Typescript's behavior when it comes to objects.</p>
<h2 id="heading-objects-in-ts">Objects In TS</h2>
<p>Objects are data structures primarily used for capturing key-value pairs. For instance, if you want to send an instance to a database, you can group the data in fields using a <code>key : "name"</code>, and the <code>values: "Kelvin", "Okuroemi"</code>. Here's one:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> infoAboutMe ={
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Kelvin"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">21</span>,
    <span class="hljs-attr">hasJob</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">hireMe</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<p>Most times, the reason TS is used when working with objects is to specify the data type of the inputs of object fields as they are used in a function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">submitResume</span>(<span class="hljs-params">{name:string, hasJob: boolean}</span>)</span>{
<span class="hljs-comment">// Some code ...</span>
}
</code></pre>
<p>As a result, calling the <code>submitResume()</code> function without an object parameter will trigger static checking.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684223105854/91e6b1d1-8866-4922-885b-f73990a556c6.png" alt class="image--center mx-auto" /></p>
<p>To stop this, we have to specify the parameters,</p>
<pre><code class="lang-javascript">submitResume({<span class="hljs-attr">name</span>: <span class="hljs-string">"Kelvin"</span>, <span class="hljs-attr">hasJob</span>: <span class="hljs-literal">false</span>})
</code></pre>
<p>Now if you wanted to specify that an object should have to return an object, you could do it by:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">submitResume</span>(<span class="hljs-params">{name:string, hasJob: boolean}</span>):</span>{isQualified: boolean}{
<span class="hljs-comment">// Some code ...</span>
<span class="hljs-keyword">return</span> {<span class="hljs-attr">isQualified</span>:<span class="hljs-literal">true</span>}
}
</code></pre>
<ul>
<li>Notice the output declaration syntax <code>:{isQualified:boolean}</code> that warrants the <code>submitResume</code> function to return a boolean in the form of an object.</li>
</ul>
<h2 id="heading-oddish">Oddish</h2>
<p>Some behaviors in TS might be able to evade TS static checking, for example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup</span>(<span class="hljs-params">{name:string}</span>)</span>{
<span class="hljs-comment">//  Some code...</span>
}
<span class="hljs-keyword">let</span> details = {<span class="hljs-attr">name</span>:<span class="hljs-string">"SideSchool"</span>, <span class="hljs-attr">rateIdea</span>: <span class="hljs-number">9.4</span>}
createStartup(details)
</code></pre>
<ul>
<li><p><code>createStartup</code> function specifies only a <code>name:string</code> parameter.</p>
</li>
<li><p><code>details</code> contain an extra field <code>rateIdea:9.4</code> and is passed on to <code>createStartup</code></p>
</li>
<li><p>However, this does not trigger static checking which is odd, because we specified only one parameter.</p>
</li>
</ul>
<p>To avoid errors like this, we use <strong>Type Aliases</strong>.</p>
<h2 id="heading-type-aliases">Type Aliases</h2>
<p>In the section before this, we tried to use variable details to specify a range of values, and it bypassed our TS static checking character. If we want to specify a range of types and still keep static checking in place, we use type aliases.</p>
<p>Type aliases help us specify a range of types to be used beforehand, and will flag errors if further components neglect the alias. Using our <code>createStartup</code> function from above:</p>
<pre><code class="lang-javascript">type Startup = {
  <span class="hljs-attr">name</span>: string;
  niche: string;
  rateIdea: number;
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup</span>(<span class="hljs-params">startup: Startup</span>): <span class="hljs-title">Startup</span> </span>{
  <span class="hljs-comment">//  Some code...</span>
  <span class="hljs-keyword">return</span> name: {<span class="hljs-string">"SideSchool"</span>,<span class="hljs-attr">niche</span>:<span class="hljs-string">"EdTech"</span>, <span class="hljs-attr">rateIdea</span>: <span class="hljs-number">9.4</span>};
}

createStartup({ <span class="hljs-attr">name</span>: <span class="hljs-string">"SideSchool"</span>, <span class="hljs-attr">niche</span>: <span class="hljs-string">"EdTech"</span>, <span class="hljs-attr">rateIdea</span>: <span class="hljs-number">9.4</span> });
</code></pre>
<ul>
<li><p>First of all, we create a type alias <code>Startup</code> with the keyword <code>type</code></p>
</li>
<li><p>Then we write that the <code>createStartup</code> function's parameter should have all the types already specified in the <code>Startup</code> type alias. It should also return a value with <code>Startup</code> type aliases.</p>
</li>
<li><p>After that, you call the function with the appropriate parameters and corresponding types as specified in the <code>Startup</code> type alias.</p>
</li>
<li><p>In this case, type aliases replace the use of the variable <code>details</code> for specifying a range of types and will trigger static checking if need be.</p>
</li>
</ul>
<p>Another reason we might use the type aliases is to prevent scenarios where we have to define the same range of types for different functions.</p>
<p><strong><em>No alias</em></strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup1</span>(<span class="hljs-params">{ name: string, cost: number }</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup2</span>(<span class="hljs-params">{ name: string, cost: number }</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup3</span>(<span class="hljs-params">{ name: string, cost: number }</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}
</code></pre>
<p><strong><em>With alisases</em></strong></p>
<pre><code class="lang-javascript">type StartupDetails = {
    <span class="hljs-attr">name</span>: string,
    <span class="hljs-attr">cost</span>: number
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup1</span>(<span class="hljs-params">details: StartupDetails</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup2</span>(<span class="hljs-params">details: StartupDetails</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createStartup3</span>(<span class="hljs-params">details: StartupDetails</span>) </span>{
  <span class="hljs-comment">//  Some code...</span>
}
</code></pre>
<p>To cap it, we can also define type aliases to accommodate unions(a choice between two or more types).</p>
<pre><code class="lang-javascript">type Union = string | number | boolean;

<span class="hljs-keyword">const</span> unionVar0: Union = <span class="hljs-string">"union"</span>;
<span class="hljs-keyword">const</span> unionVar1: Union = <span class="hljs-number">46</span>;
<span class="hljs-keyword">const</span> unionVar2: Union = <span class="hljs-literal">false</span>;
</code></pre>
<ul>
<li><p>We specify a <code>Union</code> type alias with three choices of types.</p>
</li>
<li><p>Then define all variables to have the type of <code>Union</code>, this can allow any variable to have any type already specified in <code>Union</code> type alias without triggering static checking.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>TypeScript brings significant benefits to JavaScript development, but there are peculiar behaviors when it comes to dealing with objects.</p>
<p>One crucial aspect is the use of object types in TypeScript. By explicitly specifying the data type of object fields, we can achieve static checking and catch potential errors during compilation. This helps us validate the input parameters of functions and improve code robustness.</p>
<p>However, there are instances where TypeScript's static checking may not be triggered as expected, allowing some unexpected behaviors to slip through. To address this, we can leverage Type Aliases. Type Aliases allow us to define custom types, specifying a range of expected properties. By using Type Aliases, we ensure that TypeScript enforces static checking, preventing accidental misuse of object structures.</p>
<p>Additionally, Type Aliases prove valuable when multiple functions require the same range of types. By defining a common Type Alias, we avoid redundant type definitions and promote code reusability and consistency.</p>
<p>Furthermore, Type Aliases can accommodate unions, providing flexibility in choosing between multiple types for a variable. This enables us to handle scenarios where a variable can hold values of different types without compromising static checking.</p>
<p>By mastering TypeScript's object behavior and effectively utilizing Type Aliases, we can enhance our development workflow, reduce bugs, and improve the overall quality and maintainability of our TypeScript projects.</p>
]]></content:encoded></item><item><title><![CDATA[Func-tastic TypeScript]]></title><description><![CDATA[The Magic of Functions]]></description><link>https://xylophone.hashnode.dev/func-tastic-typescript</link><guid isPermaLink="true">https://xylophone.hashnode.dev/func-tastic-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[frontend]]></category><category><![CDATA[webdev]]></category><category><![CDATA[software development]]></category><category><![CDATA[teams]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Tue, 09 May 2023 19:31:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1683745742949/9ad554db-3717-48de-99ae-7be1b7fbb6ed.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong><em>Cover photo credit:</em></strong> <a target="_blank" href="https://www.ceos3c.com/"><strong><em>Ceos3c</em></strong></a></p>
<h2 id="heading-introduction">Introduction</h2>
<p>You are reading this article because of a function (a method to be more precise). Functions make up an "underrated" most of our functional technology, and this is no different from Typescript(TS). You might understand the logic and syntax behind functions in Javascript(JS), and if you are curious to know how it works in TS, I've got you covered in this week's article.</p>
<h2 id="heading-function-inference">Function Inference</h2>
<h3 id="heading-function-with-single-parameters">Function with single parameters</h3>
<p>Check out the function below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addTwo</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}

addTwo(<span class="hljs-number">46</span>);
</code></pre>
<p>The code above looks all good, and it is. However, if we just hover around it to check its data type, it is inferred to as <code>Any</code>(Discussed in the previous article of this series). We know that's bad for our team because <code>Any</code> escape's type and static checking and attract messy bugs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683746431651/83be12b3-0efd-409d-87c2-e0e8c06f8a25.png" alt class="image--center mx-auto" /></p>
<p>We can fix this by simply mandating the parameter to be a number. Here:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Specify data type</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addTwo</span>(<span class="hljs-params">num: number</span>)</span>{
    <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>
}

addTwo(<span class="hljs-string">"46"</span>); <span class="hljs-comment">// Notice this error</span>
</code></pre>
<ul>
<li>In the code above, I threw in an error that would trigger static checking. The point you should note is that if I did not specify the data type of the number, then TS would not have noticed that error. Functions in TS have this behavior and it is up to you to specify that you don't want the inferred <code>Any</code> data type.</li>
</ul>
<h3 id="heading-function-with-multiple-parameters">Function with multiple parameters</h3>
<p>Let's have a function with multiple parameters:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">signUpUsers</span>(<span class="hljs-params">name, age, isRegistered</span>) </span>{
  <span class="hljs-built_in">console</span>.log(name, age, isRegistered);
}

signUpUsers(<span class="hljs-number">22</span>, <span class="hljs-string">"thirty-three"</span>, <span class="hljs-number">3</span>);
</code></pre>
<p>In the code above, static checking on all parameters returns each parameter as an <code>Any</code> data type. The <code>signUpUsers</code> function receives inputs that are not correct in this context, and TS can't warn us with static checking. We can simply add a data type to each parameter to avoid this.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">signUpUsers</span>(<span class="hljs-params">name: string, age: number, isRegistered: boolean</span>) </span>{
  <span class="hljs-built_in">console</span>.log(name, age, isRegistered);
}

signUpUsers(<span class="hljs-number">22</span>, <span class="hljs-string">"thirty-three"</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// error activates static checking</span>
</code></pre>
<ul>
<li>Static checking is now activated above, and we start getting those error warnings</li>
</ul>
<h3 id="heading-arrow-functions">Arrow functions</h3>
<p>Sometimes it might be necessary to use arrow functions and use default parameters, while prompting a user for input for other parameters, something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> okayLogin = <span class="hljs-function">(<span class="hljs-params">name: string, email: string, isRegistered: <span class="hljs-built_in">Boolean</span></span>) =&gt;</span> {
  <span class="hljs-comment">// Some code</span>
};

okayLogin(<span class="hljs-string">"kelvin"</span>, <span class="hljs-string">"kelvin@kelvin.com"</span>);
</code></pre>
<ul>
<li>In the last line above, the <code>isRegistered</code> parameter is not satisfied and TS static checking throws up an error.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683746670744/9822774a-f318-42da-9fcc-f178f8dd1462.png" alt class="image--center mx-auto" /></p>
<p>Assuming we wanted to set <code>isRegistered</code> to a default boolean, and also wanted TS to ignore static checking for that, we could set a default value for it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> okayLogin = <span class="hljs-function">(<span class="hljs-params">name: string, email: string, isRegistered: <span class="hljs-built_in">Boolean</span> = <span class="hljs-literal">true</span></span>) =&gt;</span> {
  <span class="hljs-comment">// Some code</span>
};

okayLogin(<span class="hljs-string">"kelvin"</span>, <span class="hljs-string">"kelvin@kelvin.com"</span>);
</code></pre>
<ul>
<li>The boolean is auto set to true except a different value is given.</li>
</ul>
<h2 id="heading-return-statements">Return statements</h2>
<h3 id="heading-single-return-statements">Single return statements</h3>
<p>For most of the function examples, we have only looked at making the input match the data type of the parameters. But can the return statements also display type errors? Let's find out. In the snippet below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">num: number</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"hello"</span>;
}
</code></pre>
<ul>
<li>Since the parameter is a number, I am also assuming that the output should be a number, but TS doesn't give any static check warnings.</li>
</ul>
<p>If this was a team with hundreds of thousands of lines of code, this would be an issue. To solve this, we have to specify the output:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">num: number</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-comment">// specify output</span>
  <span class="hljs-keyword">return</span> <span class="hljs-string">"hello"</span>; <span class="hljs-comment">// error</span>
}
</code></pre>
<ul>
<li>After specifying what should be returned, TS static checking comes into play.</li>
</ul>
<h3 id="heading-multiple-return-statements">Multiple return statements</h3>
<p>What if we had a function that could return different data types based on conditions?</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateStatus</span>(<span class="hljs-params">val: number</span>) </span>{
  <span class="hljs-keyword">if</span> (val &gt; <span class="hljs-number">5</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"status 404 not found"</span>;
  }
}
</code></pre>
<ul>
<li>The output of the function above is open to <code>any</code> data type which defeats the purpose of Typescript.</li>
</ul>
<p>Specifying a <code>return</code> statement for one data type will enforce static checking errors, so we have to specify multiple <code>return</code> statements. Like below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateStatus</span>(<span class="hljs-params">val: number</span>): <span class="hljs-title">boolean</span> | <span class="hljs-title">string</span> </span>{
  <span class="hljs-keyword">if</span> (val &gt; <span class="hljs-number">5</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"status 404 not found"</span>;
  }
}
</code></pre>
<p>It is also simple to transform the code above to an arrow function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> updateStatus = (val: number): boolean | <span class="hljs-function"><span class="hljs-params">string</span> =&gt;</span> {
  <span class="hljs-keyword">if</span> (val &gt; <span class="hljs-number">5</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"status 404 not found"</span>;
  }
};
</code></pre>
<h2 id="heading-void-and-never-functions">Void and Never functions</h2>
<p>Sometimes we might want a function that to return nothing, to do this, we specify the function to return a <code>void</code> type or a <code>never</code> type.</p>
<p><strong><em>with void</em></strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleError</span>(<span class="hljs-params">error: string</span>): <span class="hljs-title">void</span> </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(error);
}
</code></pre>
<ul>
<li>The <code>void</code> type does static checking, if any attempt to mutate the function to add a <code>return</code> statement to it.</li>
</ul>
<p><strong><em>with never</em></strong></p>
<p>Meanwhile, <code>never</code> more suited to throwing errors:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleError</span>(<span class="hljs-params">error: string</span>): <span class="hljs-title">never</span> </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(error);
}
</code></pre>
<h3 id="heading-difference-between-void-and-never">Difference between void and never</h3>
<p>In TypeScript, void and never are both used to represent the absence of a value, but they have different meanings.</p>
<p><code>void</code> is a type that represents the absence of a value. It is typically used as the return type of functions that do not return a value, or when a variable is not assigned any value. For example, the following function returns void:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logMessage</span>(<span class="hljs-params">message: string</span>): <span class="hljs-title">void</span> </span>{
  <span class="hljs-built_in">console</span>.log(message);
}
</code></pre>
<ul>
<li>In this case, the function <code>logMessage</code> does not return a value, so its return type is <code>void</code>.</li>
</ul>
<p>On the other hand, <code>never</code> is a type that represents a value that never occurs. It is typically used to indicate that a function is meant to never return a value or that a variable cannot have a value. For example, the following function returns never:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throwError</span>(<span class="hljs-params">error: string</span>): <span class="hljs-title">never</span> </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(error);
}
</code></pre>
<ul>
<li>In this case, the function <code>throwError</code> throws an error and never returns a value, so its return type is <code>never</code>.</li>
</ul>
<p>It is the intent that matters, <code>void</code> should be used to indicate that a function does not return a value, while <code>never</code> indicates that a function should never have a value.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Functions have proven themselves to be the unsung heroes of our coding escapades, and in Typescript, they take on a whole new level of charm. By harnessing the power of static type checking, we can sprinkle our functions with enchanting data types and wave goodbye to pesky bugs.</p>
<p>From inferring the right types for single and multiple parameters to crafting arrow functions with default values that tickle our coding taste buds, Typescript has us covered. It's like a magical spell that keeps our code in check, ensuring we play by the rules and catch errors before they have a chance to misbehave.</p>
<p>But it doesn't stop there! Our trusty functions can even entertain us with their return statements. We've learned how to coax them into revealing their true type identities, whether it's a single type or a delightful union of possibilities. We've witnessed the power of void, where functions gracefully bow out without returning a value, and never, the enigmatic type that assures us a value will never, ever emerge.</p>
<p>So, as we bid farewell to this journey through Typescript functions, let's remember to embrace their quirks and unleash their full potential. With static checking as our guide, we can create code that dances with joy, bringing laughter and stability to our programming endeavors. So go forth, fellow developers, and let your functions shine with all their magical might!</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript's Wildcard]]></title><description><![CDATA[The Ins and Outs of the 'any' Keyword]]></description><link>https://xylophone.hashnode.dev/typescripts-wildcard</link><guid isPermaLink="true">https://xylophone.hashnode.dev/typescripts-wildcard</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[coding]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Tue, 25 Apr 2023 10:12:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1682589688354/736f30f9-91b2-4c47-94c1-c83972a9baa7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong><em>Cover photo credit:</em></strong> <a target="_blank" href="https://www.turing.com/"><strong><em>turing.com</em></strong></a></p>
<h2 id="heading-introduction">Introduction</h2>
<p>The reason TS is so popular is because of the strict data type checking it brings to our code, but sometimes for reasons best known to you, you might want to avoid any strict checking(pun to be discovered).</p>
<p>Read on to find out how.</p>
<h2 id="heading-any">Any?</h2>
<p>Typescript(TS) is a complex tool. A complex tool should come with complex behavior. An example of such behavior is <code>any</code>. <code>any</code> is the default data type TS assigns to any variable in which it cannot infer its data type.</p>
<p>Here:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> mysteryBox;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getGift</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
};

<span class="hljs-comment">// After hundreds of lines of code and modules...</span>
mysteryBox = getGift();
<span class="hljs-built_in">console</span>.log(mysteryBox);
</code></pre>
<ul>
<li>If you hover over the last line of code(LOC), the data type of <code>mysteryBox</code> appears as <code>any</code>.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682589525257/95c45dd7-96e0-4526-9345-d67138002124.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Take, for instance, Andy a developer who was expecting the <code>mysteryBox</code> variable to return a gift string, because his teammate, Bandy told him, the code was ready for production.</p>
</li>
<li><p>Now, when Andy takes the code live, it would run into an error that might lead to other errors and break the codebase depending on the <a target="_blank" href="https://xylophone.hashnode.dev/from-good-to-great-part-1">design pattern</a>.</p>
</li>
<li><p>Allowing this type of behavior in our code can undermine the reason we use TS in the first place. It becomes easy to assign types wrongly, and bypass type safety. Hence, we should avoid using <code>any</code> data type as often as possible.</p>
</li>
</ul>
<p>Remember in the <a target="_blank" href="https://xylophone.hashnode.dev/type-it-up-exploring-typescripts-power">last article</a>, we said there are specific situations where specifying data types is good practice? This is one of those situations. If Bandy, had specified the <code>mystery box</code> as a string data type, this would have saved Andy days of debugging because of TS' static checking.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> mysteryBox : string; <span class="hljs-comment">// This triggers static checking</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getGift</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
};

<span class="hljs-comment">// After hundreds of lines of code and modules...</span>
mysteryBox = getGift();
<span class="hljs-built_in">console</span>.log(mysteryBox);
</code></pre>
<h2 id="heading-why-any">Why Any?</h2>
<p><code>Any</code> is a special type to specify on an entity(variable, function, etc) when you don't want the entity to cause a type-checking error. When you assign <code>Any</code> to an entity, any operation on it becomes legal to TS. If you do not assign a data type to an entity, TS also can infer it as <code>Any</code> data type.</p>
<p>To stop this, TS has a special property called <code>noImplicitAny</code> which we can turn on in the TS configuration file(Something we would look at in future articles).</p>
<p>Even though there might be some cases, you don't want to use any <code>Any</code> type in your TS codebase, horrible things could happen.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>TypeScript is an amazing tool that helps us catch bugs in our code before they even happen.</p>
<p>But sometimes, we just want to be rebels and avoid its strict rules, you know what I mean? That's where the <code>any</code> keyword comes in. It's like a wildcard that lets us get away with anything without getting caught! But be warned, it can be risky and cause problems down the line. So, while it's okay to use <code>any</code> sometimes, it's best to use specific data types as much as possible to keep your code safe and sound.</p>
<p>Don't forget, TypeScript is your friend, so play by the rules most of the time!</p>
]]></content:encoded></item><item><title><![CDATA[Type it Up: Exploring Typescript's Power]]></title><description><![CDATA[Types and Static Checking]]></description><link>https://xylophone.hashnode.dev/type-it-up-exploring-typescripts-power</link><guid isPermaLink="true">https://xylophone.hashnode.dev/type-it-up-exploring-typescripts-power</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[frontend]]></category><category><![CDATA[webdev]]></category><category><![CDATA[development]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Tue, 18 Apr 2023 09:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681804423675/1146a36c-c0f0-45bc-8bb4-b905be740d42.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong><em>Cover photo credit: prisma.io</em></strong></p>
<h2 id="heading-introduction">Introduction</h2>
<p>Are you tired of spending hours debugging and fixing errors in your codebase? Look no further, Typescript has got your back! Typescript is more than just a static checker, it comes with a range of features that help make your codebase safer from errors and bugs.</p>
<p>One such feature is its powerful use of types. In this article, we'll look at common types available in Typescript, learn about its general syntax and good practices, and explore the benefits of static checking.</p>
<h2 id="heading-types-an-introduction">Types, an Introduction</h2>
<p>For starters, we have normal data types like numbers, strings, and booleans. For bloomers, there are null, undefined, and void. For the retired, there are objects and tuples, and arrays. Finally, for the curious, there is more than you can dream of.</p>
<p>Working with typescripts is just mastering the kind of types, knowing their peculiarities, and how to interface them with each other. An example of why types are super useful is because we can specify the data type of inputs and outputs, and if an operation contravenes that data type, static checking comes into play.</p>
<h2 id="heading-syntax-and-static-checking">Syntax and Static Checking</h2>
<p>The general day-to-day syntax of Typescript looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> variable: type = value;
</code></pre>
<ul>
<li>The main addition of Typescript(TS) to ensure type safety and reap the full benefits of static checking is to specify the data type of any value you are adding to the codebase. Let's see how it works</li>
</ul>
<p>Check it out in the code below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> job: string =<span class="hljs-string">"Developer"</span>
<span class="hljs-built_in">console</span>.log(job)
</code></pre>
<p>Run the <code>tsc file.js</code> command to compile it to javascript. To witness TS in its full glory, let us try to assign a number to the <code>job</code> variable.</p>
<pre><code class="lang-javascript">job = <span class="hljs-number">435</span>;
</code></pre>
<p>The static checking feature of TS immediately warns us that since we specified <code>job</code> a variable as a string, we cannot assign a number to it. Neither can we assign a boolean or any other data type that is not a string.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681806942513/f6eef13a-a3b9-4de7-a1da-162f60f1911b.png" alt class="image--center mx-auto" /></p>
<p>Typescript's static checking also assists in spotting errors when working with methods. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> number = <span class="hljs-number">6</span>;
<span class="hljs-keyword">let</span> upperCase = number.toUpperCase();
</code></pre>
<p>In the code above, we declared a <code>number</code> variable and in the line below and if we try to assign the <code>toUpperCase</code> method to it on the <code>upperCase</code> variable, TS static checking warns us that the <code>toUpperCase</code> method is only applicable to strings and not numbers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681807005843/ac7e788a-a074-400d-b324-f61e79c22b98.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-every-day-types">Every day Types</h2>
<p>Wherever strings exist, types and booleans are not far behind (said by some guy).</p>
<p>These types: strings, booleans, and numbers are called <strong>Primitives</strong> in TS lingo. For strings, typescript functions as usual.</p>
<p>However, numbers come with a new feature from TS. In TS, there is no provision for integers and floats, every number is just a number data type. Booleans as usual represent true and false values.</p>
<p>To denote numbers and booleans, we just use the TS syntax while changing the type specification:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Number</span>
<span class="hljs-keyword">let</span> cardNumber : number = <span class="hljs-number">327439416823234</span>;

<span class="hljs-comment">// Boolean</span>
<span class="hljs-keyword">let</span> isValidCard : boolean = <span class="hljs-literal">true</span>;
</code></pre>
<p>And, of course, TS will only suggest potential methods based on the type specification.</p>
<h2 id="heading-type-inference">Type inference</h2>
<p>You know how we specify the data types after creating a variable like this <code>let cardNumber: number</code>? We don't need to do this. It's a bit redundant to always specify the data type, and the TS team knows this too. As a result, TS comes with a behavior called type inference where TS knows the data type because of the value assigned to the variable.</p>
<p>TS will still work and maintain its static checking(link), even though we don't specify the data type. Go on and remove the data type specification on the TS lines of code, and confirm that TS still works. It is up to you to decide whether to remove the data type specifications or not.</p>
<p>This doesn't mean that we should ignore data type specifications entirely, there will be times when it is compulsory and we will look at it in future articles.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Typescript is a powerful tool for developers to ensure type safety and avoid errors and bugs in their code.</p>
<p>With a variety of data types available and the added benefit of static checking, working with Typescript can greatly improve the quality of your code.</p>
<p>In future articles, we will explore more advanced topics such as functions, classes, objects, and much more.</p>
<p>Stay tuned to learn more about how you can take advantage of Typescript to improve your development process and create more robust applications. 📺.</p>
]]></content:encoded></item><item><title><![CDATA[Firing up TypeScript]]></title><description><![CDATA[Cover photo credit: Educative.io "Since I started using typescript, I don't want to go back to Javascript". I can't count the numerous times I have read…]]></description><link>https://xylophone.hashnode.dev/firing-up-typescript</link><guid isPermaLink="true">https://xylophone.hashnode.dev/firing-up-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[TypeScript Tutorial]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[coding]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Tue, 11 Apr 2023 09:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681192683738/97e03607-9f5b-4b06-8bfa-af9c122826bd.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong><em>Cover photo credit: Educative.io</em></strong></p>
<h2 id="heading-introduction">Introduction</h2>
<p><strong>"Since I started using typescript, I don't want to go back to Javascript".</strong></p>
<p>I can't count the numerous times I have read that comment online. So, I am going to find out if typescript is the real deal in this series. We'll go as far as we can to explore what Typescript is and how to begin using Typescript over Javascript or using both.</p>
<p>On the other hand, we will look at the significance of typescript in this article, how to install it, and write our first typescript program.</p>
<h2 id="heading-typescript-the-basics">Typescript, the basics.</h2>
<p>Tech sages online claim that Typescript(TS) is a superset of Javascript(JS), an extension of JS, and at first, I thought this brings more features to JS, and since JS is already as huge as it can get, wouldn't more features be bringing more complexity to it?</p>
<p>But TS doesn't bring complexity to JS, it even makes it better to work with. How? TS offers a compulsory feature of writing JS in a precise manner so we face lesser errors at runtime.</p>
<p>Hence, TS is primarily useful because of the rich developer experience it offers, and it doesn't bring new loops, event listeners, and switch statements. It is just a newer way of writing JS.</p>
<h3 id="heading-type-safety">Type Safety</h3>
<p>This is the uniqueness of TS. Look at the code written in JS:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> unsafe = <span class="hljs-number">22</span> + <span class="hljs-string">"22"</span>;
<span class="hljs-built_in">console</span>.log(unsafe) <span class="hljs-comment">// Outputs 2222</span>
</code></pre>
<p>You shouldn't be able to add <code>22</code>and <code>"22"</code> together, since they are different data types. TS solves this issue by making sure data types work according to their primary nature and limits unexpected behaviors. I call this WYSIWYG (What You Type Is What You Get).</p>
<h3 id="heading-static-checking">Static Checking</h3>
<p>Other languages like C#, C++, and Go are built-in with a feature called STATIC CHECKING. Static checking enables IDEs to highlight type unsafe syntax and possible errors using the language's parser() when you are writing code.</p>
<p>However, JS does not have this feature and is quiet about errors until when code is about to run, then it throws up all the errors in your face.</p>
<p>TS stops this and brings static checking to JS. This my friend, is what Typescript is all about, unstoppable Developer Experience(DX).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681195294223/b9d3fdd7-358d-40f1-9518-ff8d41113473.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>In the picture, we have an object <code>user</code> and different properties <code>name</code> and <code>age</code></p>
</li>
<li><p>Then in the next line, we try to access <code>user.school</code> , which does not exist.</p>
</li>
<li><p>TS enables static checking by hinting that the code on line 3 might be wrong</p>
</li>
</ul>
<h2 id="heading-development-process">Development process</h2>
<p>Going forward, we should know this, TS is entirely a development tool. It does not influence in production any way possible. Any code written as TS is converted to JS during compilation. In fact, a TS code that prompts errors when compiling because of TS-type safety might run perfectly on JS. Since TS is a development tool, it should allow us the freedom to set it up and modify it the way we want.</p>
<p>TS uses a special file called the <code>TS.config.js</code> to modify TS in our projects. We will look at that in later articles of this series.</p>
<p>Also, there are different ways to use Typescript, which we will look at in future articles:</p>
<ol>
<li><p>Regular Javascript, setting up the core system, and making basic TS files.</p>
</li>
<li><p>Configuring TS so it helps us produce better code.</p>
</li>
</ol>
<h3 id="heading-setting-up-typescript">Setting up Typescript</h3>
<p><strong>Step 1:</strong> Create a folder where you demonstrate and use the basics of typescript</p>
<p><strong>Step 2:</strong> Ensure node and npm are installed on your PC. To check that they are installed, run these commands on your terminal,<code>node -v</code> and <code>npm -v</code> . The version number should show up.</p>
<p><strong>Step 3:</strong> Install typescript globally with your terminal, <code>npm install -g typescript ts-node</code></p>
<p><strong>Step 4:</strong> Confirm that it is installed with this command, <code>tsc -v</code> .</p>
<h3 id="heading-firing-it-up">Firing it Up</h3>
<p>Let's use typescript, and compile it to Javascript. We need to get something clear before we move on, any code file that ends with <code>.ts</code> would not be understood by the browser, and it is not valid.</p>
<p>We have to change the typescript to a Javascript file for it to work. Typescript does not work in production. It is only a game changer in development.</p>
<p><strong>Step 1:</strong> Create a Typescript file <code>example.ts</code> in a folder of your choice.</p>
<p><strong>Step 2:</strong> Put in some dummy typescript</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> Name: <span class="hljs-string">"string"</span> = <span class="hljs-string">"string"</span>

<span class="hljs-built_in">console</span>.log(Name);
</code></pre>
<p><strong>Step 3:</strong> Run the command in terminal <code>tsc example.ts</code></p>
<p><strong>Step 4:</strong> Observe that there's an additional file <code>example.js</code> in your folder. There you go, your first typescript file.</p>
<p><strong>Please note:</strong> Even if there are errors, the typescript file will still compile to Javascript. This reiterates the fact that Typescript is just a development tool that helps you write safer and more debuggable code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Typescript offers a lot of benefits to developers by providing a more precise and type-safe way to write JavaScript.</p>
<p>It helps prevent unexpected behaviors and provides static checking, making it easier to catch errors during the development process. While it may seem like a new language, it is actually just a newer way of writing JavaScript, and any code written in Typescript is converted to JavaScript during compilation.</p>
<p>Typescript is a development tool that does not affect production code in any way, but it can significantly improve the developer experience. By following the steps outlined in this article, you can start using Typescript in your projects today and see the benefits for yourself.</p>
<p>Cheers, till we meet again 🍻.</p>
]]></content:encoded></item><item><title><![CDATA[From Good to Great: Part 3]]></title><description><![CDATA[Applying SOLID Principles in Your Code]]></description><link>https://xylophone.hashnode.dev/from-good-to-great-part-3</link><guid isPermaLink="true">https://xylophone.hashnode.dev/from-good-to-great-part-3</guid><category><![CDATA[design patterns]]></category><category><![CDATA[software development]]></category><category><![CDATA[webdevelopment]]></category><category><![CDATA[code review]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Tue, 04 Apr 2023 09:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/FYTn1u5OArU/upload/19b2e556f79049dff8fab21678a9ba3d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-gratitude">Gratitude</h2>
<p>We have learned a lot so far in the <strong><em>Modern Web Dev</em></strong> series, from understanding why we needed more web complexity to use learning about a bundler(Webpack) to learning design patterns modern internet companies used in writing their code.</p>
<p>I just want to tell you, that you are a STAR. Thanks for reading through, I appreciate it.</p>
<h2 id="heading-pre-requisites">Pre-requisites</h2>
<ul>
<li><p>JavaScript Classes</p>
</li>
<li><p>JavaScript Objects</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>Loosely Coupled Objects design is a design pattern idea closely related to the SOLID principles.</p>
<p>Loosely Coupled Objects are the opposite of tightly coupled objects, and to understand the importance of loosely coupled objects, we would take a brief description of both, a comparison, and the reasons why loosely coupled objects are better.</p>
<h2 id="heading-solid-vs-loosely-coupled-objects">SOLID vs Loosely-Coupled Objects</h2>
<p>Loosely coupled objects are a method that inspires both the Single Responsibility and Dependency-Inversion of SOLID.</p>
<p>It ensures that a piece of code does not depend too much on outside pieces of code and advocates for making code as modular as possible.</p>
<p>However, The main difference between loosely-coupled objects and the SOLID principles is that loosely-coupled objects are a general concept that can apply to any programming paradigm or design pattern, whereas the SOLID principles are specific guidelines for object-oriented programming.</p>
<p>In the context of the SOLID principles, loose coupling is typically achieved by adhering to the Dependency Inversion Principle (DIP), which states that modules should not depend directly on other modules, but instead should depend on abstractions.</p>
<p>This means that code should be designed in such a way that the implementation details of one module can be easily changed without affecting other modules that depend on it.</p>
<h2 id="heading-coupling">Coupling</h2>
<p>Coupling refers to how closely two or more components(Classes, functions, etc.) are closely connected or dependent on each other.</p>
<p>When two components are tightly coupled with each other, it means they are highly dependent on each other and any change made on one will warrant an equal change in one or will lead to breaking.</p>
<p>On the other hand, when components are loosely coupled, they can still depend on each other vaguely. A change in one component might not lead to an entire failure.</p>
<p>If we were developing an app that takes in input and thanks customers after receiving input, tightly coupling this app could likely mean that for the app to take input from the customer, it has to thank the customer.</p>
<p>But what if the thank function was not working? It means our receiving input app will not work. Although there is not one way of loosely coupling objects, the key is to ensure that there is not a single point of failure, meaning that the failure of one component should not entirely lead to the failure of another.</p>
<p>There can be coupling between components, and our goal is to reduce the failures arising from their interaction. Let's look at some code examples of tight and loose coupling.</p>
<h3 id="heading-tight-coupling">Tight Coupling</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">num1, num2</span>) </span>{
  <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> num1 = <span class="hljs-number">5</span>;
  <span class="hljs-keyword">let</span> num2 = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">let</span> total = addNumbers(num1, num2);
  <span class="hljs-built_in">console</span>.log(total);
}
</code></pre>
<ul>
<li>The <code>calculateTotal</code> function depends on the <code>addNumbers</code> function. If we were to change the parameters of <code>addNumbers</code> or the way it calculates the result, it could break the <code>calculateTotal</code> function.</li>
</ul>
<h3 id="heading-loose-coupling">Loose Coupling</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">num1, num2</span>) </span>{
  <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params">num1, num2</span>) </span>{
  <span class="hljs-keyword">let</span> total = addNumbers(num1, num2);
  <span class="hljs-built_in">console</span>.log(total);
}
</code></pre>
<ul>
<li>Although the <code>calculateTotal</code> function uses <code>addNumbers</code> in its code block, it is less likely to fail because it takes its own parameters, and you can add a change to the <code>addNumbers</code> function, and worry less about it breaking.</li>
</ul>
<h3 id="heading-error-demo">Error Demo</h3>
<p>If you are like me, you are wondering what kind of errors could occur from an example as simple as this. Here's one using the same examples in the previous two sections:</p>
<p><strong>Tight coupling error:</strong> Using the same code snippet for tight coupling</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">num1, num2, num3</span>) </span>{ <span class="hljs-comment">//Change</span>
  <span class="hljs-keyword">return</span> num1 + num2 + num3; <span class="hljs-comment">// Change</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> num1 = <span class="hljs-number">5</span>;
  <span class="hljs-keyword">let</span> num2 = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">let</span> total = addNumbers(num1, num2);
  <span class="hljs-built_in">console</span>.log(total);
}

calculateTotal();
</code></pre>
<ul>
<li><p>If you run the <code>calculateTotal</code> the function above, it doesn't work.</p>
</li>
<li><p>What is returned is <code>NaN</code>, this happens because since the <code>calculateTotal</code> function is entirely dependent on the <code>addNumbers</code> function even for parameters, it has to have three numbers called inside it.</p>
</li>
</ul>
<p><strong>Solution:</strong> To solve this, we need to add a third <code>num3</code> variable to the code snippet.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">num1, num2, num3</span>) </span>{
  <span class="hljs-keyword">return</span> num1 + num2 + num3;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> num1 = <span class="hljs-number">5</span>;
  <span class="hljs-keyword">let</span> num2 = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">let</span> num3 = <span class="hljs-number">12</span>; <span class="hljs-comment">// Solution</span>
  <span class="hljs-keyword">let</span> total = addNumbers(num1, num2, num3); <span class="hljs-comment">// Solution</span>
  <span class="hljs-built_in">console</span>.log(total);
}

calculateTotal();
</code></pre>
<p><strong>Loose coupling error<em>:</em></strong> Now let's use the code snippet in the loose coupling section,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">num1, num2, num3</span>) </span>{
  <span class="hljs-keyword">return</span> num1 + num2 + num3;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params">num1, num2</span>) </span>{
  <span class="hljs-keyword">let</span> total = addNumbers(num1, num2);
  <span class="hljs-built_in">console</span>.log(total);
}

calculateTotal(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>);
</code></pre>
<ul>
<li><p>Now run <code>calculateTotal</code> and you see, IT WORKS!!!</p>
</li>
<li><p><code>calculateTotal</code> is only trying to access two parameters with <code>addNumbers</code> and it can do because of how it's designed.</p>
</li>
</ul>
<p>There's no underlying algorithm that makes this happen, it's just design patterns. Now, this is amazing.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Loosely coupled objects are an important design pattern that advocates for code modularity, and it is a general concept that applies to any programming paradigm or design pattern.</p>
<p>In comparison, tightly coupled objects are highly dependent on each other, and any change in one component will lead to the breaking of another.</p>
<p>Our goal as developers is to reduce the failures arising from the interaction between components, and one way to achieve this is through loose coupling.</p>
<p>By implementing loose coupling, we can reduce the probability of a single point of failure in our code, which will make our applications more robust and resilient to changes.</p>
]]></content:encoded></item><item><title><![CDATA[From Good to Great: Part 2]]></title><description><![CDATA[Learn the easiest way to start writing web code like the pro you want to be]]></description><link>https://xylophone.hashnode.dev/from-good-to-great-part-2</link><guid isPermaLink="true">https://xylophone.hashnode.dev/from-good-to-great-part-2</guid><category><![CDATA[webdev]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[software development]]></category><category><![CDATA[Clean Architecture]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Tue, 28 Mar 2023 09:00:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/inI8GnmS190/upload/20aa13ee1fdd00411331dc4a9d0730a5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-pre-requisite">Pre-requisite</h2>
<ul>
<li><p>Javascript Classes</p>
</li>
<li><p>Javascript Objects</p>
</li>
<li><p>Es6 import and export</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>Welcome, faithful developer. I hope you took out time to use the SOLID patterns we discussed in the <a target="_blank" href="https://xylophone.hashnode.dev/from-good-to-great-part-1">previous article</a>.</p>
<p>In today's article, we will be storming through and looking at the remaining two of SOLID and how to apply it to our codebase:</p>
<ul>
<li><p>Interface Segregation</p>
</li>
<li><p>Dependency Inversion</p>
</li>
</ul>
<h2 id="heading-interface-segregation">Interface Segregation</h2>
<p>Although Javascript doesn't have the ability of interfaces, we can replicate the same behavior with class inheritance. This principle states that any descendant class must use all properties of its ancestor.</p>
<p>If we had a Bird class, the properties of the bird would be to run, swim and fly, and if we wanted to make a Dog class, we could just inherit the Bird class, since Dog should be able to run and swim.</p>
<p>However, the Interface Segregation principle states that this inheritance is faulty, the Dog class does not use all the properties i.e flying off the Bird class.</p>
<p>Let's write some code.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Entity</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, attackDamage, health) {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.attackDamage = attackDamage;
    <span class="hljs-built_in">this</span>.health = health;
  }

  move() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> moved`</span>);
  }

  attack(target) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> attacked <span class="hljs-subst">${target.name}</span> for
        <span class="hljs-subst">${<span class="hljs-built_in">this</span>.attackDamage}</span> damage`</span>);
    target.takeDamage(<span class="hljs-built_in">this</span>.attackDamage);
  }

  takeDamage(amount) {
    <span class="hljs-built_in">this</span>.health -= amount;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> has <span class="hljs-subst">${<span class="hljs-built_in">this</span>.health}</span> health remaining`</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Character</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Entity</span> </span>{}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Wall</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Entity</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, health) {
    <span class="hljs-built_in">super</span>(name, <span class="hljs-number">0</span>, health);
  }

  move() {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }

  attack() {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Turret</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Entity</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, attackDamage) {
    <span class="hljs-built_in">super</span>(name, attackDamage, <span class="hljs-number">-1</span>);
  }

  move() {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }

  takeDamage() {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
}

<span class="hljs-keyword">const</span> turret = <span class="hljs-keyword">new</span> Turret(<span class="hljs-string">"Turret"</span>, <span class="hljs-number">5</span>);
<span class="hljs-keyword">const</span> character = <span class="hljs-keyword">new</span> Character(<span class="hljs-string">"Character"</span>, <span class="hljs-number">3</span>, <span class="hljs-number">100</span>);
<span class="hljs-keyword">const</span> wall = <span class="hljs-keyword">new</span> Wall(<span class="hljs-string">"Wall"</span>, <span class="hljs-number">200</span>);

turret.attack(character);
character.move();
character.attack(wall);
</code></pre>
<ul>
<li><p>In this code, the <code>Entity</code> class is made up of more methods, <code>move()</code>,<code>attack()</code>, <code>takeDamage()</code>, and its descendants <code>Character</code>,<code>Wall</code>,<code>Turret</code> inherit one or more methods from it.</p>
</li>
<li><p>The <code>Wall</code> and <code>Turret</code> classes inherit the <code>takeDamage()</code> and <code>attack()</code> methods respectively but exclude the other methods. Meanwhile the <code>Character</code> the class takes all three.</p>
</li>
<li><p>This means that the <code>Wall</code> and <code>Turret</code> classes do not satisfy the Interface Segregation principle.</p>
</li>
</ul>
<p><strong><em>Solution:</em></strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Implement the interfaces in separate classes</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Entity</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Character</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Entity</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, attackDamage, health) {
    <span class="hljs-built_in">super</span>(name);
    <span class="hljs-built_in">this</span>.attackDamage = attackDamage;
    <span class="hljs-built_in">this</span>.health = health;
  }

  move() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> moved`</span>);
  }

  attack(target) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> attacked <span class="hljs-subst">${target.name}</span> for
            <span class="hljs-subst">${<span class="hljs-built_in">this</span>.attackDamage}</span> damage`</span>);
    target.takeDamage(<span class="hljs-built_in">this</span>.attackDamage);
  }

  takeDamage(amount) {
    <span class="hljs-built_in">this</span>.health -= amount;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> has <span class="hljs-subst">${<span class="hljs-built_in">this</span>.health}</span> health remaining`</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Wall</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Entity</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, health) {
    <span class="hljs-built_in">super</span>(name);
    <span class="hljs-built_in">this</span>.health = health;
  }

  takeDamage(amount) {
    <span class="hljs-built_in">this</span>.health -= amount;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> has <span class="hljs-subst">${<span class="hljs-built_in">this</span>.health}</span> health remaining`</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Turret</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Entity</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, attackDamage) {
    <span class="hljs-built_in">super</span>(name);
    <span class="hljs-built_in">this</span>.attackDamage = attackDamage;
  }

  attack(target) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> attacked <span class="hljs-subst">${target.name}</span> for
            <span class="hljs-subst">${<span class="hljs-built_in">this</span>.attackDamage}</span> damage`</span>);
    target.takeDamage(<span class="hljs-built_in">this</span>.attackDamage);
  }
}

<span class="hljs-comment">// Use the classes to create instances and call their methods</span>

<span class="hljs-keyword">const</span> turret = <span class="hljs-keyword">new</span> Turret(<span class="hljs-string">"Turret"</span>, <span class="hljs-number">5</span>);
<span class="hljs-keyword">const</span> character = <span class="hljs-keyword">new</span> Character(<span class="hljs-string">"Character"</span>, <span class="hljs-number">3</span>, <span class="hljs-number">100</span>);
<span class="hljs-keyword">const</span> wall = <span class="hljs-keyword">new</span> Wall(<span class="hljs-string">"Wall"</span>, <span class="hljs-number">200</span>);

turret.attack(character);
character.move();
character.attack(wall);
</code></pre>
<ul>
<li><p>To satisfy the Interface Segregation principle, we made the <code>Entity</code> class smaller, to only pass off a name as an inheritance to its descendant classes.</p>
</li>
<li><p>All Classes now contain only methods that they implement.</p>
</li>
</ul>
<p>And with that, the Interface Segregation principle is satisfied.</p>
<h2 id="heading-dependency-inversion">Dependency Inversion</h2>
<p>With the interfaces segregated, let's look at the last design pattern of SOLID: Dependency Inversion.</p>
<p>The Dependency Inversion principle is simply against two classes being too dependent on each other. It is similar to the Open/Closed principle but more related to the relationship between two classes.</p>
<p>Imagine, if you were making a robot that talks and a robot that runs. To change the way the robot walks, you might have to change the way the talks because the control of the robot's ability to walk and talk is linked together.</p>
<p>This is what the Dependency Inversion principle is against, you should be able to change the way the robot walks without changing the way the robot talks.</p>
<p>And, if both abilities must be linked, then there should be an abstraction between them, that can serve as a placeholder for one attribute in another but won't necessarily be the attribute itself.</p>
<p>First, a POC(Piece of Code) that violates the Dependency Inversion principle:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Waiter</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">this</span>.order = <span class="hljs-literal">null</span>;
  }

  takeOrder(customer) {
    <span class="hljs-built_in">this</span>.order = customer.placeOrder();
  }

  deliverOrder() {
    <span class="hljs-keyword">const</span> chef = <span class="hljs-keyword">new</span> Chef();
    chef.cook(<span class="hljs-built_in">this</span>.order);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chef</span> </span>{
  cook(order) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${order}</span> is served hot and sizzling`</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Customer</span> </span>{
  placeOrder() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Biryani"</span>;
  }
}

<span class="hljs-keyword">const</span> waiter = <span class="hljs-keyword">new</span> Waiter();
<span class="hljs-keyword">const</span> customer = <span class="hljs-keyword">new</span> Customer();
waiter.takeOrder(customer);
waiter.deliverOrder();
</code></pre>
<ul>
<li><p>Check out the <code>deliverOrder()</code> method in the <code>Waiter</code> class, it has to call a <code>Chef</code> class inside of it.</p>
</li>
<li><p>If perhaps we wanted to update our <code>Waiter</code> to use a <code>Chef2</code> class, we would need to modify the <code>Waiter</code> class and this violates the Dependency Inversion principle.</p>
</li>
</ul>
<p><strong><em>Solution:</em></strong></p>
<p>We should develop an interface, so that even if we change the <code>Chef</code> class, any class that has a <code>cook</code> method which will work with the <code>Waiter</code> class</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Waiter</span> </span>{
  <span class="hljs-keyword">constructor</span>(chef) {
    <span class="hljs-built_in">this</span>.order = <span class="hljs-literal">null</span>;
    <span class="hljs-built_in">this</span>.chef = chef;
  }

  takeOrder(customer) {
    <span class="hljs-built_in">this</span>.order = customer.placeOrder();
  }

  deliverOrder() {
    <span class="hljs-comment">// Dependency Inversion</span>
    <span class="hljs-built_in">this</span>.chef.cook(<span class="hljs-built_in">this</span>.order);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chef</span> </span>{
  cook(order) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${order}</span> is served hot and sizzling`</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Customer</span> </span>{
  placeOrder() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Biryani"</span>;
  }
}

<span class="hljs-keyword">const</span> chef = <span class="hljs-keyword">new</span> Chef(); <span class="hljs-comment">// Dependency Inversion</span>
<span class="hljs-keyword">const</span> waiter = <span class="hljs-keyword">new</span> Waiter(chef);
<span class="hljs-keyword">const</span> customer = <span class="hljs-keyword">new</span> Customer();
waiter.takeOrder(customer);
waiter.deliverOrder();
</code></pre>
<ul>
<li><p>The <code>Waiter</code> the class now takes a <code>chef</code> parameter which can be any class.</p>
</li>
<li><p>The <code>Chef</code> class is no longer written inside called inside <code>Waiter</code> class.</p>
</li>
<li><p>This property <code>this.chef</code>, can now work with any class that has a <code>cook</code> method.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We have seen how to apply the SOLID design principles of Interface Segregation and Dependency Inversion in our JavaScript code.</p>
<p>We learned that Interface Segregation can be implemented by creating separate classes to implement the interfaces instead of inheriting all methods from one parent class and not using some methods.</p>
<p>Dependency Inversion is against two classes being too dependent on each other and can be modified without affecting each other. By applying these principles, we can write better, maintainable, and scalable code.</p>
<p>For the next article titled "Loosely Coupled Objects," we will dive deeper into the concept of decoupling objects and its benefits in creating clean code. We will look at how we can achieve loosely coupled objects by applying the Dependency Injection pattern and other techniques.</p>
<p>Stay tuned!</p>
]]></content:encoded></item><item><title><![CDATA[From Good to Great: Part 1]]></title><description><![CDATA[Applying SOLID Principles in Your Code]]></description><link>https://xylophone.hashnode.dev/from-good-to-great-part-1</link><guid isPermaLink="true">https://xylophone.hashnode.dev/from-good-to-great-part-1</guid><category><![CDATA[webdevelopment]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[software development]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Kelvin Okuroemi]]></dc:creator><pubDate>Tue, 21 Mar 2023 09:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/4Xy08NbMBLM/upload/d1eaefd873b134424b4ecf71d7b93e28.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-pre-requisites">Pre-requisites</h2>
<ul>
<li><p>Javascript objects</p>
</li>
<li><p>Javascript classes</p>
</li>
<li><p>ES6 import and export modules</p>
</li>
</ul>
<h2 id="heading-introduction">Introduction</h2>
<p>Apart from just writing classes and objects, we also need to neatly convey concepts like Inheritance and Composition. To write better cleaner code as web developers, there are guidelines to ensure we keep to efficient standards.</p>
<p>Two standards for this are</p>
<ul>
<li><p>The <strong><em>SOLID</em></strong> principle contains five design patterns for writing efficient code.</p>
</li>
<li><p>Loosely coupled objects. Related to SOLID but a bit different.</p>
</li>
</ul>
<p>In this article and the next, we would look at how modern web developers write Javascript code with SOLID principles and loosely coupled objects, and why they are important for efficiency.</p>
<h2 id="heading-solid">SOLID</h2>
<p>The SOLID principle stands for five design patterns or sub principles which are:</p>
<ul>
<li><p>Single Responsibility</p>
</li>
<li><p>Open/Closed</p>
</li>
<li><p>Liskov Substitution</p>
</li>
<li><p>Interface Segregation</p>
</li>
<li><p>Dependency Inversion</p>
</li>
</ul>
<p>You can use as many as all or as little as none when writing code, this has made life less stressful for developers worldwide, and you and I shouldn't have to suffer.</p>
<h3 id="heading-single-responsibility">Single Responsibility</h3>
<p>Touted as the most important and the most straightforward, this principle indicates that a class should not have more than one method or at least, have methods that do the same thing in the same class.</p>
<p>Let's have an example of a class that has methods mashed into it.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MeterTracker</span> </span>{
  <span class="hljs-keyword">constructor</span>(maxMeter) {
    <span class="hljs-built_in">this</span>.maxMeter = maxMeter;
    <span class="hljs-built_in">this</span>.currentMeter = <span class="hljs-number">0</span>;
  }

  trackMeter(meter) {
    <span class="hljs-built_in">this</span>.currentMeter += meter;
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.currentMeter &gt; <span class="hljs-built_in">this</span>.maxMeter) {
      <span class="hljs-built_in">this</span>.showExcess();
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">this</span>.support();
    }
  }

  restRunner() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Get some rest"</span>);
  }

  supportRunner() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Keep running"</span>);
  }
}

<span class="hljs-keyword">const</span> runMeter = <span class="hljs-keyword">new</span> MeterTracker(<span class="hljs-number">2000</span>);
runMeter.trackMeter(<span class="hljs-number">500</span>);
runMeter.trackMeter(<span class="hljs-number">400</span>);
runMeter.trackMeter(<span class="hljs-number">200</span>);
runMeter.trackMeter(<span class="hljs-number">1500</span>);
</code></pre>
<ul>
<li><p>In the code above, we want to design a function that adds and keeps note of meters being run, and we do this by designing a class. All is fine with the <code>MeterTracker</code> tracker class until we bring the Single Responsibility(SR) principle into play.</p>
</li>
<li><p>There is more than one method in our class, <code>trackMeter()</code>, <code>restRunner()</code>, and <code>supportRunner()</code>.</p>
</li>
<li><p>Obviously, this is against the SR principle and we have to change it. To adhere to this principle, we should take two methods out of the class. Let's do this with the import/export statements.</p>
</li>
</ul>
<p><strong>Solution:</strong></p>
<ol>
<li>Create a separate file In this file we are going to put our <code>restRunner()</code> and <code>supportRunner()</code> methods and import them in this file.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">restRunner</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Get some rest"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">supportRunner</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Keep running"</span>);
}

<span class="hljs-keyword">export</span> { restRunner, supportRunnner };
</code></pre>
<ol>
<li>Import them into the main file</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { supportRunner,restRunner } <span class="hljs-keyword">from</span> <span class="hljs-string">"./SR.js"</span>
</code></pre>
<ol>
<li>Change the <code>MeterTracker</code> class to use the imported functions</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { supportRunner, restRunner } <span class="hljs-keyword">from</span> <span class="hljs-string">"./SR.js"</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MeterTracker</span> </span>{
  <span class="hljs-keyword">constructor</span>(maxMeter) {
    <span class="hljs-built_in">this</span>.maxMeter = maxMeter;
    <span class="hljs-built_in">this</span>.currentMeter = <span class="hljs-number">0</span>;
  }

  trackMeter(meter) {
    <span class="hljs-built_in">this</span>.currentMeter += meter;
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.currentMeter &gt; <span class="hljs-built_in">this</span>.maxMeter) {
      restRunner();
    } <span class="hljs-keyword">else</span> {
      support();
    }
  }
}

<span class="hljs-keyword">const</span> runMeter = <span class="hljs-keyword">new</span> MeterTracker(<span class="hljs-number">2000</span>);
runMeter.trackMeter(<span class="hljs-number">500</span>);
runMeter.trackMeter(<span class="hljs-number">400</span>);
runMeter.trackMeter(<span class="hljs-number">200</span>);
runMeter.trackMeter(<span class="hljs-number">1500</span>);
</code></pre>
<ul>
<li>Everything should work as before, we only have one method <code>trackMeter</code> in our <code>MeterTracker</code> class.</li>
</ul>
<p>A wise man once said:</p>
<blockquote>
<p><strong>Don't put functions that change for different reasons in the same class.</strong></p>
<p>-Uncle Bob</p>
</blockquote>
<h3 id="heading-openclosed">Open/Closed</h3>
<p>This principle can be a bit tricky but can be understood with use. The Open/Closed principle states that a class, module, and function should be closed for modification but open for extension.</p>
<p>Let's use a code sample that does not follow the Open-Closed (OC) principle.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> questions = [
  {
    <span class="hljs-attr">type</span>: <span class="hljs-string">"boolean"</span>,
    <span class="hljs-attr">info</span>: <span class="hljs-string">"Do you really like coding or just the money"</span>,
  },
  {
    <span class="hljs-attr">type</span>: <span class="hljs-string">"multipleChoice"</span>,
    <span class="hljs-attr">info</span>: <span class="hljs-string">"What's your best thing to do?"</span>,
    <span class="hljs-attr">options</span>: [<span class="hljs-string">"Sleep"</span>, <span class="hljs-string">"Eat"</span>, <span class="hljs-string">"Work"</span>, <span class="hljs-string">"Anime"</span>, <span class="hljs-string">"Twitter"</span>],
  },
  {
    <span class="hljs-attr">type</span>: <span class="hljs-string">"text"</span>,
    <span class="hljs-attr">info</span>: <span class="hljs-string">"What's your biggest motivation in life"</span>,
  },
];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printQuiz</span>(<span class="hljs-params">questions</span>) </span>{
  questions.forEach(<span class="hljs-function">(<span class="hljs-params">question</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(question.info);
    <span class="hljs-keyword">switch</span> (question.type) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">"boolean"</span>:
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"1. Yes"</span>);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"2. Naaah,the mula"</span>);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"3. I'm not sure"</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">"multipleChoice"</span>:
        question.options.forEach(<span class="hljs-function">(<span class="hljs-params">option, index</span>) =&gt;</span> {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${index + <span class="hljs-number">1</span>}</span>. <span class="hljs-subst">${option}</span>`</span>);
        });
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">"text"</span>:
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"______________"</span>);
        <span class="hljs-keyword">break</span>;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ALL GOOD?"</span>);
    }
  });
}

printQuiz(questions);
</code></pre>
<ul>
<li><p>Even though the code above works, if we want to add a new question to our <code>questions</code> array, we would need to also change the <code>switch</code> statement in our <code>printQuiz()</code> function. This is what violates the Open Closed rule.</p>
</li>
<li><p>The rule is if we want to change anything outside the <code>printQuiz()</code> function, we should not change code inside the <code>printQuiz()</code> function. Trust me, I was shocked as you are when I first heard this, but there's a way to go around this.</p>
</li>
<li><p>Just so you know, almost every time we have multiple <code>if</code> or <code>switch</code> statements, it is almost certain we are violating the Open Closed rule.</p>
</li>
</ul>
<p><strong>Solution</strong>:</p>
<p>Let's break the <code>printQuiz()</code> function into smaller classes, so we don't have to write a lot of logic inside it.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BooleanQuestion</span> </span>{
  <span class="hljs-keyword">constructor</span>(info) {
    <span class="hljs-built_in">this</span>.info = info;
  }

  printChoices() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"1. Yes"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"2. Naaah,the mula"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"3. I'm not sure"</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MultipleChoiceQuestion</span> </span>{
  <span class="hljs-keyword">constructor</span>(info, options) {
    <span class="hljs-built_in">this</span>.info = info;
    <span class="hljs-built_in">this</span>.options = options;
  }

  printChoices() {
    <span class="hljs-built_in">this</span>.options.forEach(<span class="hljs-function">(<span class="hljs-params">option, index</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${index + <span class="hljs-number">1</span>}</span>. <span class="hljs-subst">${option}</span>`</span>);
    });
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TextQuestion</span> </span>{
  <span class="hljs-keyword">constructor</span>(info) {
    <span class="hljs-built_in">this</span>.info = info;
  }
  printChoices() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"_____________"</span>);
  }
}

<span class="hljs-keyword">const</span> questions = [
  <span class="hljs-keyword">new</span> BooleanQuestion(<span class="hljs-string">"Do you really coding or just the money"</span>),
  <span class="hljs-keyword">new</span> MultipleChoiceQuestion(<span class="hljs-string">"What's your best thing to do?"</span>, [
    <span class="hljs-string">"Sleep"</span>,
    <span class="hljs-string">"Eat"</span>,
    <span class="hljs-string">"Work"</span>,
    <span class="hljs-string">"Anime"</span>,
    <span class="hljs-string">"Twitter"</span>,
  ]),
  <span class="hljs-keyword">new</span> TextQuestion(<span class="hljs-string">"What's your biggest motivation in life"</span>)
];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printQuiz</span>(<span class="hljs-params">questions</span>) </span>{
  questions.forEach(<span class="hljs-function">(<span class="hljs-params">question</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(question.info);
    question.printChoices();
  });
}

printQuiz(questions);
</code></pre>
<ul>
<li><p>We created three new classes, <code>BooleanQuestion</code> ,<code>MultipleChoiceQuestion</code> , and <code>TextQuestion</code> .</p>
</li>
<li><p>We then used the classes to create new entries in the <code>questions</code> array.</p>
</li>
<li><p>Now isn't that gorgeous? Our function <code>printQuiz</code> is smaller, and we don't have to touch to add a new detail.</p>
</li>
</ul>
<p>Let's make a new class, and use the <code>new</code> keyword to construct additional information in the <code>questions</code> array. Change your code to look like this.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add new Class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RangeQuestion</span> </span>{
  <span class="hljs-keyword">constructor</span>(info) {
    <span class="hljs-built_in">this</span>.info = info;
  }
  printChoices() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"1-5"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"4-6"</span>);
  }
}
<span class="hljs-keyword">const</span> questions = [
  <span class="hljs-keyword">new</span> BooleanQuestion(<span class="hljs-string">"Do you really coding or just the money"</span>),
  <span class="hljs-keyword">new</span> MultipleChoiceQuestion(<span class="hljs-string">"What's your best thing to do?"</span>, [
    <span class="hljs-string">"Sleep"</span>,
    <span class="hljs-string">"Eat"</span>,
    <span class="hljs-string">"Work"</span>,
    <span class="hljs-string">"Anime"</span>,
    <span class="hljs-string">"Twitter"</span>,
  ]),
  <span class="hljs-keyword">new</span> TextQuestion(<span class="hljs-string">"What's your biggest motivation in life"</span>),
  <span class="hljs-comment">// Add new question to the array using RangeQuestion class</span>
  <span class="hljs-keyword">new</span> RangeQuestion(<span class="hljs-string">"Range of your coding confidence?"</span>)
];
</code></pre>
<p>Mutating our functions with huge <code>if</code> and <code>switch</code> could lead to buggy code, really buggy code. But we've avoided that in this example.</p>
<p>Even though we EXTENDED the abilities of our <code>printQuiz()</code> function, we never had to MODIFY it. Now, isn't that impressive?</p>
<h3 id="heading-liskov-substitution">Liskov Substitution</h3>
<p>We are at the <strong>L</strong> part of SO<strong>L</strong>ID, which would be the last for today's piece, you need some rest. To the cute name, Liskov.</p>
<p>This deviates a bit from the message of the singularity of code to deal with inheritance.</p>
<p>Liskov Substitution advocates that if a class is a descendant of another class, it should be able to work in the place of its ancestor without any issue. As usual, let's write code that violates the Liskov Substitution principle.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span> </span>{
  <span class="hljs-keyword">constructor</span>(width, height) {
    <span class="hljs-built_in">this</span>.width = width;
    <span class="hljs-built_in">this</span>.height = height;
  }

  setWidth(width) {
    <span class="hljs-built_in">this</span>.width = width;
  }

  setHeight(height) {
    <span class="hljs-built_in">this</span>.height = height;
  }

  calculateArea() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.width * <span class="hljs-built_in">this</span>.height;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Rectangle</span> </span>{
  setWidth(width) {
    <span class="hljs-built_in">this</span>.width = width;
    <span class="hljs-built_in">this</span>.height = width;
  }

  setHeight(height) {
    <span class="hljs-built_in">this</span>.width = height;
    <span class="hljs-built_in">this</span>.height = height;
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">increaseRectangleWidth</span>(<span class="hljs-params">rectangle</span>) </span>{
  rectangle.setWidth(rectangle.width + <span class="hljs-number">1</span>);
}

<span class="hljs-keyword">const</span> rectangle1 = <span class="hljs-keyword">new</span> Rectangle(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>);
<span class="hljs-keyword">const</span> rectangle2 = <span class="hljs-keyword">new</span> Rectange(<span class="hljs-number">5</span>, <span class="hljs-number">5</span>); 

increaseRectangleWidth(rectangle1);
increaseRectangleWidth(rectangle2);

<span class="hljs-built_in">console</span>.log(rectangle1.calculateArea());
<span class="hljs-built_in">console</span>.log(rectangle2.calculateArea());
</code></pre>
<ul>
<li>The answers we get are <code>25</code> and <code>30</code>, if we change the <code>Rectangle</code> construct to a class <code>Square</code> construct, it should do the same thing, but it does not.</li>
</ul>
<pre><code class="lang-javascript">- <span class="hljs-keyword">const</span> rectangle2 = <span class="hljs-keyword">new</span> Rectange(<span class="hljs-number">5</span>, <span class="hljs-number">5</span>); 
+ <span class="hljs-keyword">const</span> rectangle2 = <span class="hljs-keyword">new</span> Square(<span class="hljs-number">5</span>, <span class="hljs-number">5</span>);
</code></pre>
<ul>
<li>We get <code>25</code> and <code>36</code>. The <code>Square</code> class changes the code's behavior through the <code>increaseRectangleWidth()</code> function, even though it is a descendant of the <code>Rectangle</code> class.</li>
</ul>
<p><strong>Solution</strong>:</p>
<p>This goes against everything the Liskov Substitution stands for, and although it is a bit tricky, it could be satisfied. A simple way to fulfill this is to simply change the <code>Square class</code> to look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Rectangle</span> </span>{
  setSize(size) {
    <span class="hljs-built_in">this</span>.width = size;
    <span class="hljs-built_in">this</span>.height = size;
  }
}
</code></pre>
<ul>
<li>The <code>Square</code> class has a new method <code>setSize</code> that doesn't change the behavior and can replace the <code>Rectangle</code> class.</li>
</ul>
<p>Let me reiterate, the Liskov principle warrants every descendant class to work in any function its ancestors can work in without changing how the code works.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Single Responsibility, Open-closed, and Liskov principles form the foundation of the SOLID principles.</p>
<p>These principles are essential in software design and web development as they ensure that the code is maintainable, extensible, and robust. By adhering to these principles, developers can create high-quality software that is easy to understand, modify, and test.</p>
<p>However, these three principles are just the tip of the iceberg. The remaining SOLID principles, namely Interface Segregation and Dependency Inversion, are equally important and complement the first three principles.</p>
<p>In the next article, we will delve into these two principles and see how they complete the SOLID principles. Stay tuned for more insights on creating better software through SOLID principles.</p>
]]></content:encoded></item></channel></rss>