<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ url - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ url - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 06 May 2026 17:00:33 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/url/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use URLs for State Management in React ]]>
                </title>
                <description>
                    <![CDATA[ For years, URLs have been synonymous with web navigation. But the tide is turning, especially with the emergence of single-page applications. In the React universe, URLs are stepping up to play a pivotal role in state management. This article will gu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-urls-for-state-management-in-react/</link>
                <guid isPermaLink="false">66bb890b7a6500a14ba5b769</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ routing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ David Jaja ]]>
                </dc:creator>
                <pubDate>Fri, 06 Oct 2023 17:50:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/Article-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>For years, URLs have been synonymous with web navigation. But the tide is turning, especially with the emergence of single-page applications. In the React universe, URLs are stepping up to play a pivotal role in state management.</p>
<p>This article will guide you through the transformative journey of URLs as state managers in the context of React applications. </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>Fundamentals of HTML and CSS</li>
<li>Fundamentals of ES6 JavaScript</li>
<li>Fundamentals of React, React Router and React Hooks.</li>
</ul>
<h2 id="heading-the-evolution-of-state-management-in-react">The Evolution of State Management in React</h2>
<p>Let's journey through the past:</p>
<ul>
<li><strong>setState</strong>: In the early days of React, many relied on component state, especially within <a target="_blank" href="https://react.dev/reference/react/Component#defining-a-class-component">class components</a>. It was straightforward to manage component-specific data. But it wasn't ideal for larger applications.</li>
<li><strong>Redux &amp; MobX</strong>: As applications grew in complexity, tools like <a target="_blank" href="https://redux.js.org/">Redux</a> and <a target="_blank" href="https://mobx.js.org/README.html">MobX</a> emerged. They centralized data management, making it easier to handle app-wide data.</li>
<li><strong>Context API &amp; Hooks</strong>: React's own <a target="_blank" href="https://react.dev/reference/react/useContext">Context API</a>, combined with the advent of hooks, brought about a more native way to manage the global state without adding extra libraries.</li>
</ul>
<h2 id="heading-managing-state-with-urls">Managing State with URLs</h2>
<p>At first, using a URL for managing state might seem unusual. But as you explore further, you'll discover several clear benefits:</p>
<ul>
<li><strong>Save Your Spot</strong>: By keeping state in the URL, your webpage remembers your place. So, if you bookmark a page, it will look the same when you come back to it later.</li>
<li><strong>Easy Sharing</strong>: If you're looking at something specific on a page, like a product or a chart, you can share the URL. Anyone who clicks it will see exactly what you’re seeing, making collaboration a breeze.</li>
<li><strong>Troubleshoot with Ease</strong>: Developers can find and fix issues faster because the URL shows the state of the app. They can see problems just by clicking on the shared link.</li>
</ul>
<p>In short, using URLs in this way helps keep your spot, share specific views, and makes problem-solving smoother for developers.</p>
<h2 id="heading-how-to-implement-url-based-state-management">How to Implement URL-based State Management</h2>
<p>Considering the size of this section, here’s everything you’ll learn.</p>
<ol>
<li>How to Set Up the Environment</li>
<li>Clearing the clutter</li>
<li>Project Breakdown / Analysis</li>
<li>Install the Necessary Dependencies</li>
<li>How to Fetch the Data and Design the UI</li>
<li>How to Store State in the URL</li>
<li>How to Read the State Stored in the URL</li>
<li>How to Customize the Product Page</li>
</ol>
<h3 id="heading-how-to-set-up-the-environment">How to Set Up the Environment</h3>
<p>Open your inbuilt terminal or code editor’s terminal (preferably) and run the following:</p>
<pre><code class="lang-bash">npm create vite@latest
</code></pre>
<p>This command uses <a target="_blank" href="https://vitejs.dev/guide/">Vite</a> (a lightweight tool that is used for building fast and optimized web applications) to scaffold a web app environment. Navigate down using your arrow keys and select React.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/02-Selecting-React.png" alt="Image" width="600" height="400" loading="lazy">
<em>Selecting React from Vite Setup</em></p>
<p>Then select your preferred language combination – I’ll be using plain JS.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/03-Selecting-JS.png" alt="Image" width="600" height="400" loading="lazy">
<em>Selecting Language in React</em></p>
<p>Next, move into your react folder using the cd “project-name” folder and run <code>npm install</code> to install all the project’s dependencies.</p>
<p>Finally, start the development server by running <code>npm run dev</code> and going to the respective URL (<a target="_blank" href="http://localhost:5173/">http://localhost:5173/</a>).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/04-dev-server-running.png" alt="Image" width="600" height="400" loading="lazy">
<em>Dev Server running</em></p>
<h3 id="heading-clearing-the-clutter">Clearing the clutter</h3>
<p>Make sure to clear the contents of all the CSS files and delete the <code>App.css</code> as you’ll need only 1 style file. Then, clear the contents of the <code>App</code> component and replace it with basic JSX content.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/05-clutter-cleared.png" alt="Image" width="600" height="400" loading="lazy">
<em>Clutter Cleared in Dev Environment</em></p>
<p>This returns a clear page on your local server that looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/06-clear-server-page.png" alt="Image" width="600" height="400" loading="lazy">
<em>Clear Server page</em></p>
<h3 id="heading-project-breakdown-analysis">Project breakdown / analysis</h3>
<p>The project involves getting data from an API and persisting that data globally via the URL to be accessible across many components/pages.</p>
<p>A relatable example is when you’re on your favourite e-commerce site, you may see this cool gadget and want to share it with your friend.</p>
<p>You usually share the link from the browser to your friend’s social media DM which they can use to view the same product without any fuss by opening the link you sent to them.</p>
<p>Here’s a sneaky peek at the project we're going to build: 😉</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/1-sneaky-peek.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Sneaky peek of complete project</em></p>
<p>Intrigued?🌚 Let’s dive in then.</p>
<h3 id="heading-install-the-necessary-dependencies">Install the necessary dependencies</h3>
<p>Before you put anything on the page, you must first fully configure your development environment with the necessary dependencies.</p>
<ul>
<li><a target="_blank" href="https://www.npmjs.com/package/json-server">json-server</a>: This package hosts your data on a local server, enabling you to fetch it like an external API.</li>
<li><a target="_blank" href="https://www.npmjs.com/package/react-router">react-router</a>: This package enables React to create SPAs that allow navigating without refreshing the page.</li>
</ul>
<pre><code class="lang-bash">npm i json-server react-router-dom
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/08-installing-dependencies-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Installing dependencies</em></p>
<ul>
<li>Then download the JSON data from this <a target="_blank" href="https://github.com/Daiveedjay/URL-State-Management/tree/main/data">GitHub(json-data)</a>, and the assets from this <a target="_blank" href="https://github.com/Daiveedjay/URL-State-Management/tree/main/public/assets">GitHub(assets-data)</a>.</li>
</ul>
<p>Now create a data folder in your root project directory and place the JSON file inside. Then create an assets folder in your public directory and place all images in that assets folder.</p>
<p>Your current folder structure should be like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/07-folder-structure-after-downloading-files.png" alt="Image" width="600" height="400" loading="lazy">
<em>Folder structure after downloading files</em></p>
<p>Next, modify your package.json file by adding a script which starts up the json-server</p>
<pre><code class="lang-json"><span class="hljs-string">"server"</span>: <span class="hljs-string">"json-server --watch data/products.json --port 9000 "</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/09-adding-a-server-script.png" alt="Image" width="600" height="400" loading="lazy">
<em>Adding server script to package.json</em></p>
<p>After that, open your terminal and start up the server with <code>npm run server</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/10-starting-data-server.png" alt="Image" width="600" height="400" loading="lazy">
<em>Starting data server</em></p>
<p>With this, your server is running and the content of your JSON file can be accessed through the URL provided.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/11-data-on-browser.png" alt="Image" width="600" height="400" loading="lazy">
<em>Data on Browser</em></p>
<p>Ps: If you want to view JSON files in the browser like I do, download the browser extension – <a target="_blank" href="https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh">JSON Viewer</a>.</p>
<h3 id="heading-how-to-fetch-the-data-and-design-the-ui">How to fetch the data and design the UI</h3>
<p>Start by creating a HomePage component and importing it into the App component. This component will contain all the data in the first screen you saw earlier.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/12-importing-the-homepage.png" alt="Image" width="600" height="400" loading="lazy">
<em>Importing the Homepage</em></p>
<p>In the <code>HomePage</code> component, use a <code>useEffect</code> hook to fetch all the data from your local API.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">HomePage</span>(<span class="hljs-params"></span>) </span>{
  useEffect(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{

      <span class="hljs-keyword">try</span>{
      <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"http://localhost:9000/products"</span>);
      <span class="hljs-keyword">const</span> clothesData = <span class="hljs-keyword">await</span> res.json();
      <span class="hljs-built_in">console</span>.log(clothesData);   
      }
      <span class="hljs-keyword">catch</span> (error) {  <span class="hljs-built_in">console</span>.log(error);}
      }
    fetchData();
  }, []);

  <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">"homepage"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Homepage of my Dummy Product Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span>
  );
}
</code></pre>
<p>At the moment, you can already view the data fetched in the console.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/13-evidence-of-fetching-data.png" alt="Image" width="600" height="400" loading="lazy">
<em>Evidence of data fetching</em></p>
<p>Next, store your data in a state using the <code>useState</code> hook and populate your interface with that data.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">HomePage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [products, setProducts] = useState([]);

  useEffect(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"http://localhost:9000/products"</span>);
        <span class="hljs-keyword">const</span> clothesData = <span class="hljs-keyword">await</span> res.json();
        <span class="hljs-built_in">console</span>.log(clothesData);
        <span class="hljs-comment">//Storing happens here</span>
        setProducts(clothesData);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
      }
    }
    fetchData();
  }, []);

  <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">"homepage"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Homepage of my Dummy Product Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"products__list"</span>&gt;</span>
        {products.map((product) =&gt; (
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
            <span class="hljs-attr">key</span>=<span class="hljs-string">{product.id}</span>
                      <span class="hljs-attr">className</span>=<span class="hljs-string">"product__item"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">loading</span>=<span class="hljs-string">"lazy"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{product.imageUrl}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{product.itemName}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</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">main</span>&gt;</span></span>
  );
}
</code></pre>
<p>All the styling required in this project is in this <a target="_blank" href="https://github.com/Daiveedjay/URL-State-Management/blob/main/src/index.css">CSS file</a>. Alternatively, you can paste these stylings in your index.css, which gives the same result.</p>
<pre><code class="lang-css"><span class="hljs-keyword">@import</span> url(<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Nunito:wght@400;700&amp;display=swap"</span>);

*,
<span class="hljs-selector-pseudo">::before</span>,
<span class="hljs-selector-pseudo">::after</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-tag">html</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">62.5%</span>;
}
<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Nunito"</span>, sans-serif;
}

<span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">700</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">3rem</span>;

  &amp; span {
    <span class="hljs-attribute">cursor</span>: pointer;
    <span class="hljs-attribute">margin-right</span>: <span class="hljs-number">3rem</span>;
  }
}

<span class="hljs-selector-tag">a</span>,
<span class="hljs-selector-tag">h3</span> {
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#a04000</span>;
}

<span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">display</span>: block;
  <span class="hljs-attribute">transition</span>: all ease-in <span class="hljs-number">0.3s</span>;
}

<span class="hljs-selector-class">.homepage</span> {
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">3rem</span>;

  &amp; &gt; * {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  }
}

<span class="hljs-selector-class">.products__list</span> {
  <span class="hljs-attribute">column-count</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">column-gap</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">2rem</span>;

  &amp; &gt; * {
    <span class="hljs-attribute">break-inside</span>: avoid;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">2rem</span>;
  }

  &amp; <span class="hljs-selector-class">.product__item</span> {
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">1rem</span>;
    <span class="hljs-attribute">overflow</span>: hidden;
    <span class="hljs-attribute">display</span>: block;
    <span class="hljs-attribute">position</span>: relative;
    <span class="hljs-attribute">transition</span>: all ease-in <span class="hljs-number">0.3s</span>;

    &amp; h2 {
      <span class="hljs-attribute">background</span>: <span class="hljs-number">#fff</span>;
      <span class="hljs-attribute">bottom</span>: <span class="hljs-number">5px</span>;
      <span class="hljs-attribute">left</span>: <span class="hljs-number">5px</span>;
      <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.5rem</span> <span class="hljs-number">1rem</span>;
      <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
      <span class="hljs-attribute">z-index</span>: <span class="hljs-number">2</span>;
      <span class="hljs-attribute">position</span>: absolute;
      <span class="hljs-attribute">transition</span>: all ease-in <span class="hljs-number">0.3s</span>;
    }

    &amp;<span class="hljs-selector-pseudo">:hover</span> <span class="hljs-selector-tag">img</span> {
      <span class="hljs-attribute">scale</span>: <span class="hljs-number">1.1</span>;
    }

    &amp;<span class="hljs-selector-pseudo">:hover</span> <span class="hljs-selector-tag">h2</span> {
      <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(<span class="hljs-number">10px</span>, -<span class="hljs-number">10px</span>);
    }
  }
}

<span class="hljs-selector-class">.single__product</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">4rem</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">overflow</span>: hidden;

  &amp; section {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">justify-content</span>: center;
    <span class="hljs-attribute">flex-direction</span>: column;

    &amp; figure {
      <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">1rem</span>;
      <span class="hljs-attribute">overflow</span>: hidden;

      &amp; .product__img {
        <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
      }
    }

    &amp; <span class="hljs-selector-tag">aside</span> {
      <span class="hljs-attribute">display</span>: flex;
      <span class="hljs-attribute">flex-direction</span>: column;
      <span class="hljs-attribute">justify-content</span>: flex-end;
      <span class="hljs-attribute">padding</span>: <span class="hljs-number">1.5rem</span>;

      &amp; &gt; h2 {
        <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2.5rem</span>;
      }
      &amp; &gt; <span class="hljs-selector-tag">h3</span> {
        <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.6rem</span>;
      }
      &amp; <span class="hljs-selector-tag">span</span> {
        <span class="hljs-attribute">background</span>: <span class="hljs-built_in">rgba</span>(<span class="hljs-number">160</span>, <span class="hljs-number">64</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.5</span>);
        <span class="hljs-attribute">padding-inline</span>: <span class="hljs-number">1rem</span>;
        <span class="hljs-attribute">align-self</span>: flex-start;
      }
    }
  }
}

<span class="hljs-comment">/* Small devices (portrait tablets and large phones, 600px and up) */</span>
<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">600px</span>) {
  <span class="hljs-selector-class">.products__list</span> {
    <span class="hljs-attribute">column-count</span>: <span class="hljs-number">2</span>;
  }

  <span class="hljs-selector-class">.single__product</span> {
    &amp; section {
      <span class="hljs-attribute">flex-direction</span>: row;

      &amp; .product__img {
        <span class="hljs-attribute">max-width</span>: <span class="hljs-number">300px</span>;
      }
    }
  }
}

<span class="hljs-comment">/* Medium devices (landscape tablets, 768px and up) */</span>
<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-selector-class">.homepage</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">2rem</span> <span class="hljs-number">4rem</span>;
  }
  <span class="hljs-selector-class">.products__list</span> {
    <span class="hljs-attribute">column-count</span>: <span class="hljs-number">3</span>;
  }
}
</code></pre>
<p>At the moment, your home page should already look identical to the demo version.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/14-page-with-styings-applied.png" alt="Image" width="600" height="400" loading="lazy">
<em>Home page with styles added</em></p>
<h3 id="heading-how-to-store-state-in-the-url">How to store state in the URL</h3>
<p>In order to manage and share state across multiple pages using the URL, you first need to define routes using the react-router package.</p>
<p>Start by creating a route for the homepage:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { BrowserRouter, Route, Routes } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;

<span class="hljs-keyword">import</span> HomePage <span class="hljs-keyword">from</span> <span class="hljs-string">"./HomePage"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</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">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">index</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">HomePage</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>
  );
}
</code></pre>
<ul>
<li>The <strong>BrowserRouter</strong> component wraps your entire application or the part of your app where you want to use routing.</li>
<li>The <strong>Routes</strong> component wraps all your <strong>Route</strong> components and is responsible for rendering the first route that matches the current location. </li>
<li>The <strong>Route</strong> component represents a single route in your application.</li>
</ul>
<p>Next, create a <code>ProductItem</code> component responsible for showing a single item and its equivalent route.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { BrowserRouter, Route, Routes } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;

<span class="hljs-keyword">import</span> HomePage <span class="hljs-keyword">from</span> <span class="hljs-string">"./Homepage"</span>;
<span class="hljs-keyword">import</span> ProductItem <span class="hljs-keyword">from</span> <span class="hljs-string">"./ProductItem"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</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">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">index</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">HomePage</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">"product"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">ProductItem</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>
  );
}
</code></pre>
<p>To view the <code>ProductItem</code> component, head over to your <code>HomePage</code> and wrap each individual product with a <code>Link</code> element pointing to the product page with their unique ID.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<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">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">HomePage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [products, setProducts] = useState([]);

  useEffect(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"http://localhost:9000/products"</span>);

      <span class="hljs-keyword">const</span> clothesData = <span class="hljs-keyword">await</span> res.json();
      <span class="hljs-built_in">console</span>.log(clothesData);
      setProducts(clothesData);
    }
    fetchData();
  }, []);

  <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">"homepage"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Homepage of my Dummy Product Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"products__list"</span>&gt;</span>
        {products.map((product) =&gt; (
          <span class="hljs-tag">&lt;<span class="hljs-name">Link</span>
            <span class="hljs-attr">key</span>=<span class="hljs-string">{product.id}</span>
           // <span class="hljs-attr">Moving</span> <span class="hljs-attr">to</span> <span class="hljs-attr">the</span> <span class="hljs-attr">product</span> <span class="hljs-attr">page</span>
           <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>`/<span class="hljs-attr">product</span>?<span class="hljs-attr">id</span>=<span class="hljs-string">${product.id}</span>`}
            <span class="hljs-attr">className</span>=<span class="hljs-string">"product__item"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">loading</span>=<span class="hljs-string">"lazy"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{product.imageUrl}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{product.itemName}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">Link</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">main</span>&gt;</span></span>
  );
}
</code></pre>
<p>Clicking on any product now routes you to the product page and shows the <code>ProductItem</code> component.</p>
<p>On closer observation, you may notice that the id of each item is appended to the URL via its id property (for example: product?id=12345678).  This implies that you have successfully stored the id state to the URL.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/02-confirming-id-state-shared.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-read-the-state-stored-in-the-url">How to read the state stored in the URL</h3>
<p>In order to show data for each product, you have to read the state stored in the URL.</p>
<p>To implement this, start by creating a new custom hook (this helps for reusability). In your custom hook, import the <code>useSearchParams</code> hook.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useSearchParams } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useURLID</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [searchParams] = useSearchParams();
}
</code></pre>
<p>The <code>useSearchParams</code> hook allows you to interact with the query parameters of the URL (part of the URL that comes after the ? as seen in your URL earlier).</p>
<p>In order to retrieve the values from the URL, use the <code>get</code> method and pass in the name of the value you want to retrieve, in this case, the <code>id</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useSearchParams } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useURLID</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [searchParams] = useSearchParams();
  <span class="hljs-keyword">const</span> id = searchParams.get(<span class="hljs-string">"id"</span>);
  <span class="hljs-keyword">return</span> { id };
}
</code></pre>
<p>To test out your hook, import it into the <code>ProductItem</code> page and extract the values.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useURLID } <span class="hljs-keyword">from</span> <span class="hljs-string">"./useURLID"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductItem</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { id } = useURLID();
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Product Item {id}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/2-confirming-id-state-shared.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And voilà! Your id state is now global and can used by any component in your app. Bravo!</p>
<h3 id="heading-how-to-customize-the-product-page">How to customize the Product Page</h3>
<p>In order to fully achieve what was shown in the demo, perform another fetch based on the id to get the data for that product.</p>
<p>Start by creating states to store the data and account for the data loading.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [singleProduct, setSingleProduct] = useState({});
<span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">false</span>);
</code></pre>
<p>Then use a <code>useEffect</code> hook to fetch and store the data based on the unique product id.</p>
<pre><code class="lang-js">  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
      setLoading(<span class="hljs-literal">true</span>);
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`http://localhost:9000/products/<span class="hljs-subst">${id}</span>`</span>);

        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();

        setSingleProduct(data);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
      } <span class="hljs-keyword">finally</span> {
        setLoading(<span class="hljs-literal">false</span>);
      }
    }
    fetchData();
  }, [id]);
</code></pre>
<p>Next, use the data received to populate the interface.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useURLID } <span class="hljs-keyword">from</span> <span class="hljs-string">"./useURLID"</span>;


<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductItem</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { id } = useURLID();
  <span class="hljs-keyword">const</span> [singleProduct, setSingleProduct] = useState({});
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">false</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
      setLoading(<span class="hljs-literal">true</span>);
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`http://localhost:8000/products/<span class="hljs-subst">${id}</span>`</span>);

        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();

        setSingleProduct(data);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
      } <span class="hljs-keyword">finally</span> {
        setLoading(<span class="hljs-literal">false</span>);
      }
    }
    fetchData();
  }, [id]);



  <span class="hljs-comment">// If loading, display the loading div</span>
  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-comment">// If not loading, display the product details</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">"single__product"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>
               <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>
          {singleProduct.itemName} Page id: {id}
        <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">figure</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"product__img-container"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"product__img"</span>
            <span class="hljs-attr">src</span>=<span class="hljs-string">{singleProduct.imageUrl}</span>
            <span class="hljs-attr">alt</span>=<span class="hljs-string">"Image"</span>
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">figure</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">aside</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{singleProduct.itemName}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>{singleProduct.notes}<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>
            Category: <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{singleProduct.type}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
            Width: <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>{singleProduct?.size?.width}<span class="hljs-tag">&lt;/<span class="hljs-name">strong</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>
            Length: <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>{singleProduct?.size?.length}<span class="hljs-tag">&lt;/<span class="hljs-name">strong</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">aside</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Finally, account for easy navigation by providing a back button to go to the home page. You can do this using the <code>useNavigate</code> hook in react-router. This hook provides a function that allows you to programmatically navigate to other parts of your application. </p>
<p>Simply import the <code>useNavigate</code> hook, and initialize it with a variable like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useNavigate } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
<span class="hljs-keyword">const</span> navigate = useNavigate();
</code></pre>
<p>Then call this function with an event handler, and pass in the home page route.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useURLID } <span class="hljs-keyword">from</span> <span class="hljs-string">"./useURLID"</span>;
<span class="hljs-keyword">import</span> { useNavigate } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductItem</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { id } = useURLID();
  <span class="hljs-keyword">const</span> [singleProduct, setSingleProduct] = useState({});
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">false</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
      setLoading(<span class="hljs-literal">true</span>);
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`http://localhost:9000/products/<span class="hljs-subst">${id}</span>`</span>);

        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();

        setSingleProduct(data);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
      } <span class="hljs-keyword">finally</span> {
        setLoading(<span class="hljs-literal">false</span>);
      }
    }
    fetchData();
  }, [id]);

  <span class="hljs-keyword">const</span> navigate = useNavigate();

  <span class="hljs-comment">// If loading, display the loading div</span>
  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-comment">// If not loading, display the product details</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">"single__product"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>
       // Navigate to the home page
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> navigate("/")}&gt;🔙 <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>
          {singleProduct.itemName} Page id: {id}
        <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">figure</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"product__img-container"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"product__img"</span>
            <span class="hljs-attr">src</span>=<span class="hljs-string">{singleProduct.imageUrl}</span>
            <span class="hljs-attr">alt</span>=<span class="hljs-string">"Image"</span>
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">figure</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">aside</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{singleProduct.itemName}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>{singleProduct.notes}<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>
            Category: <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{singleProduct.type}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
            Width: <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>{singleProduct?.size?.width}<span class="hljs-tag">&lt;/<span class="hljs-name">strong</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>
            Length: <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>{singleProduct?.size?.length}<span class="hljs-tag">&lt;/<span class="hljs-name">strong</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">aside</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Testing your final result now gives the following:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/final-take-1.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Final take showing all features</em></p>
<h2 id="heading-real-world-examples">Real-World Examples</h2>
<ul>
<li><strong>E-commerce platforms</strong>: Think of sites like Amazon. They use URLs to let you share specific product searches or settings. Thanks to this, people can easily share their favourite items or shopping lists with friends.</li>
<li><strong>Data Tools</strong>: Tools like <a target="_blank" href="https://www.tableau.com/">Tableau</a> save your custom views in the URL. This means teams can share specific data pictures with each other, making talks, shows, and decisions faster and clearer.</li>
</ul>
<h3 id="heading-additional-information">Additional Information</h3>
<p>I’d like to point out a couple of things in the article not highlighted.</p>
<ul>
<li>The CSS used contains <a target="_blank" href="https://developer.chrome.com/articles/css-nesting/">native CSS nesting</a> that isn’t fully supported by all browsers, so if there are UI irregularities you notice, it may be from the browser you’re using. Feel free to switch to a browser like Google Chrome for better support or check for browser support with a tool like <a target="_blank" href="https://caniuse.com/">CanIUse</a> and add polyfills to your code.</li>
<li>If this article delved into things that were a tad complicated for you (how routing works), feel free to check out this article on <a target="_blank" href="https://www.freecodecamp.org/news/improve-user-experience-in-react-by-animating-routes-using-framer-motion/">Routing Animations</a> for a better understanding.</li>
<li>If you’re interested in the full code, here’s the repo, <a target="_blank" href="https://github.com/Daiveedjay/URL-State-Management">GitHub</a>, and the Live version is here. <a target="_blank" href="https://free-code-camp-url-state-manangement.netlify.app/">Demo</a></li>
<li>As an added feature, I made the code fully responsive for anyone interested in creating masonry grids for future projects, cheers!🍷</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>React's state management has evolved, with URL-based state emerging as a standout. This method not only simplifies state management but also fosters collaboration and transparency between users and developers.</p>
<p>So, the next time you're online and think of sharing data via a URL, remember that you have the tools to implement this feature yourself 😉. It's a nudge for developers to explore the untapped potential of URLs in state management.</p>
<h3 id="heading-contact-information">Contact Information</h3>
<p>Want to connect or contact me? Feel free to hit me up on the following:</p>
<ul>
<li>Twitter / X: <a target="_blank" href="https://twitter.com/JajaDavid8">@jajadavid8</a></li>
<li>LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/david-jaja-8084251b4/">David Jaja</a></li>
<li>Email: <a target="_blank" href="mailto:Jajadavidjid@gmail.com">Jajadavidjid@gmail.com</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Validate URLs in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ A Uniform Resource Locator (URL) is what leads you to a page or file on the internet. URLs serve as the addresses of things on the internet. All valid URLs follow certain patterns. So if you know those patterns, you can determine whether a URL is val... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-validate-urls-in-javascript/</link>
                <guid isPermaLink="false">66d45dde51f567b42d9f8447</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 22 Nov 2022 04:12:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/jase-bloor-oCZHIa1D4EU-unsplash--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A Uniform Resource Locator (URL) is what leads you to a page or file on the internet. URLs serve as the addresses of things on the internet.</p>
<p>All valid URLs follow certain patterns. So if you know those patterns, you can determine whether a URL is valid or not in your program and give feedback, throw an error, and so on.</p>
<p>In this tutorial, you will learn three methods to check if a string in JavaScript is a valid URL:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-url-constructor-to-validate-urls">How to Use the <code>URL</code> Constructor to Validate URLs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-npm-packages-to-validate-urls">How to Use npm Packages to Validate URLs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-regex-to-validate-urls">How to Use Regex to Validate URLs</a></p>
</li>
</ul>
<h2 id="heading-how-to-use-the-url-constructor-to-validate-urls">How to Use the <code>URL</code> Constructor to Validate URLs</h2>
<p>When you pass a string to the <code>URL</code> constructor, it returns a new <code>URL</code> object if a string is a valid URL. Otherwise, it returns an error:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fccUrl = <span class="hljs-keyword">new</span> URL(<span class="hljs-string">"https://www.freecodecamp.org/"</span>);
<span class="hljs-built_in">console</span>.log(fccUrl);
</code></pre>
<p>The following is what you get when you log <code>fccUrl</code> to the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/validURL.PNG" alt="A URL object in JavaScript" width="600" height="400" loading="lazy"></p>
<p><em>A</em> <code>URL</code> object in JavaScript</p>
<p>This object means that the string you passed to the <code>URL</code> constructor was a valid URL.</p>
<p>Now let's see what you get when you pass an invalid URL string:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fccUrl = <span class="hljs-keyword">new</span> URL(<span class="hljs-string">'freecodecamp'</span>);
<span class="hljs-built_in">console</span>.log(fccUrl);
</code></pre>
<p>The string <code>'freecodecamp'</code> is not a valid URL. Thus, you get the following <code>TypeError</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/invalidURL.PNG" alt="A TypeError after passing an invalid URL to the URL constructor" width="600" height="400" loading="lazy"></p>
<p><em>Invalid URL</em></p>
<p>To recap:</p>
<ol>
<li><p>When you pass a valid URL string to the <code>URL</code> constructor, it returns a new <code>URL</code> object.</p>
</li>
<li><p>When you pass an invalid URL string to the <code>URL</code> constructor, it returns a <code>TypeError</code>.</p>
</li>
</ol>
<p>With this knowledge, you can create a custom function to check the validity of a given URL string.</p>
<h3 id="heading-how-to-create-a-url-validator-function-with-the-url-constructor">How to Create a URL Validator Function with the <code>URL</code> Constructor</h3>
<p>By using the <code>URL</code> constructor and a <code>try...catch</code> statement, you can create a custom <code>isValidUrl</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidUrl</span>(<span class="hljs-params">string</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">new</span> URL(string);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p>The <code>isValidUrl</code> function returns <code>true</code> when the string you pass as an argument is a valid URL. Otherwise, it returns <code>false</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'mailto://mail@freecodecamp.org'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'freecodecamp'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-how-to-validate-only-http-urls-with-the-url-constructor">How to Validate Only HTTP URLs with the <code>URL</code> Constructor</h3>
<p>Sometimes, you may want to check if the string is a valid HTTP URL, and reject other valid URLs like <code>'mailto://mail@freecodecamp.org'</code>.</p>
<p>If you look closely at the <code>URL</code> object, one of its properties is <code>protocol</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/protocol.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>URL</code> object has a protocol property.</p>
<p>In the example above, the value of the protocol property is <code>'https:'</code>.</p>
<p>To check if a string is a valid HTTP URL, you can use the protocol property of the URL object:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidHttpUrl</span>(<span class="hljs-params">string</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> newUrl = <span class="hljs-keyword">new</span> URL(string);
    <span class="hljs-keyword">return</span> newUrl.protocol === <span class="hljs-string">'http:'</span> || newUrl.protocol === <span class="hljs-string">'https:'</span>;
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}

<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'mailto://mail@freecodecamp.org'</span>)); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'freecodecamp'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>The difference here is that you're not returning <code>true</code> after the new <code>URL</code> object is created. Instead, you're checking if the <code>protocol</code> property has a value equal to <code>'http:'</code> or <code>'https:'</code> and returning <code>true</code> if it is and <code>false</code> if not.</p>
<h2 id="heading-how-to-use-npm-packages-to-validate-urls">How to Use npm Packages to Validate URLs</h2>
<p>There are two NPM packages you can use: <code>is-url</code> and <code>is-url-http</code>.</p>
<p>These packages are the simplest way to check if a string is a valid URL. All you need to do is pass in a string as a parameter, and they will return <code>true</code> or <code>false</code>.</p>
<p>Let's see how both of these packages work.</p>
<h3 id="heading-how-to-validate-urls-with-the-is-url-package">How to Validate URLs with the <code>is-url</code> Package</h3>
<p>You can use the <code>is-url</code> package to check if a string is a valid URL. This package does not check the protocol of the URL passed to it.</p>
<p>To use <code>is-url</code>, first install it using the command below:</p>
<pre><code class="lang-javascript">npm install is-url
</code></pre>
<p>Then import it and pass your URL string to it as an argument:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> isUrl <span class="hljs-keyword">from</span> <span class="hljs-string">'is-url'</span>;

<span class="hljs-keyword">const</span> firstCheck = isUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>);
<span class="hljs-keyword">const</span> secondCheck = isUrl(<span class="hljs-string">'mailto://mail@freecodecamp.org'</span>);
<span class="hljs-keyword">const</span> thirdCheck = isUrl(<span class="hljs-string">'freeCodeCamp'</span>);

<span class="hljs-built_in">console</span>.log(firstCheck); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(secondCheck); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(thirdCheck); <span class="hljs-comment">// false</span>
</code></pre>
<p>The <code>is-url</code> package returns <code>true</code> for strings that have valid URL formats and <code>false</code> for strings that have invalid URL formats.</p>
<p>In the example, both <code>firstCheck</code> (with the <code>https:</code> protocol) and <code>secondCheck</code> (with the <code>mailto:</code> protocol) return <code>true</code>.</p>
<h3 id="heading-how-to-validate-http-urls-with-the-is-http-url-package">How to Validate HTTP URLs with the <code>is-http-url</code> Package</h3>
<p>You can use the <code>is-url-http</code> package to check if a string is a valid HTTP URL.</p>
<p>Install the package with the following command:</p>
<pre><code class="lang-javascript">npm install is-url-http
</code></pre>
<p>Then import it and pass the URL string to it like so:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> isUrlHttp <span class="hljs-keyword">from</span> <span class="hljs-string">'is-url-http'</span>;

<span class="hljs-keyword">const</span> firstCheck = isUrlHttp(<span class="hljs-string">'https://www.freecodecamp.org/'</span>);
<span class="hljs-keyword">const</span> secondCheck = isUrlHttp(<span class="hljs-string">'mailto://freecodecamp@mail.org'</span>);
<span class="hljs-keyword">const</span> thirdCheck = isUrlHttp(<span class="hljs-string">'freeCodeCamp'</span>);

<span class="hljs-built_in">console</span>.log(firstCheck); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(secondCheck); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(thirdCheck); <span class="hljs-comment">// false</span>
</code></pre>
<p>In this example, only <code>firstCheck</code> returns <code>true</code>. The <code>is-url-http</code> package is not only checks that the string is a valid URL, it also checks if it's a valid HTTP URL. That is why it returns <code>false</code> for <code>secondCheck</code>, which is not a valid HTTP URL.</p>
<h2 id="heading-how-to-use-regex-to-validate-urls">How to Use Regex to Validate URLs</h2>
<p>You can also use regex, or a regular expression, to check if a string is a valid URL or not.</p>
<p>All valid URLs follow a particular pattern. They have three main parts, which are:</p>
<ul>
<li><p>Protocol</p>
</li>
<li><p>Domain name (or IP address)</p>
</li>
<li><p>Port and path</p>
</li>
</ul>
<p>Sometimes a query string or fragment locator follows the path.</p>
<p>You can learn more about URL patterns from this <a target="_blank" href="https://www.freecodecamp.org/news/what-happens-when-you-hit-url-in-your-browser/">freeCodeCamp article on the structure of URLs</a>.</p>
<p>Knowing the pattern URLs are made of, you can use regex to check for the existence of such patterns in a string. If the patterns exist, then the string passes the regex test. Otherwise, it fails.</p>
<p>Also, using regex, you can check for all valid URLs, or only check for valid HTTP URLs.</p>
<h3 id="heading-how-to-validate-urls-with-regex">How to Validate URLs with Regex</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidUrl</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">const</span> pattern = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(
    <span class="hljs-string">'^([a-zA-Z]+:\\/\\/)?'</span> + <span class="hljs-comment">// protocol</span>
      <span class="hljs-string">'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'</span> + <span class="hljs-comment">// domain name</span>
      <span class="hljs-string">'((\\d{1,3}\\.){3}\\d{1,3}))'</span> + <span class="hljs-comment">// OR IP (v4) address</span>
      <span class="hljs-string">'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'</span> + <span class="hljs-comment">// port and path</span>
      <span class="hljs-string">'(\\?[;&amp;a-z\\d%_.~+=-]*)?'</span> + <span class="hljs-comment">// query string</span>
      <span class="hljs-string">'(\\#[-a-z\\d_]*)?$'</span>, <span class="hljs-comment">// fragment locator</span>
    <span class="hljs-string">'i'</span>
  );
  <span class="hljs-keyword">return</span> pattern.test(str);
}

<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'mailto://freecodecamp.org'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'freeCodeCamp'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>The regex in the <code>isValidUrl</code> function above checks if a string is a valid URL. The protocol check <code>^([a-zA-Z]+:\\/\\/)?</code> is not limited to just <code>https:</code>.</p>
<p>This is why the second example with the <code>mailto:</code> protocol returns <code>true</code>.</p>
<h3 id="heading-how-to-validate-http-urls-with-regex">How to Validate HTTP URLs with Regex</h3>
<p>To use regex to check if a string is a valid HTTP URL, you need to edit the protocol check.</p>
<p>Instead of <code>^([a-zA-Z]+:\\/\\/)?</code>, you should use <code>'^(https?:\\/\\/)?'</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidHttpUrl</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">const</span> pattern = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(
    <span class="hljs-string">'^(https?:\\/\\/)?'</span> + <span class="hljs-comment">// protocol</span>
      <span class="hljs-string">'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'</span> + <span class="hljs-comment">// domain name</span>
      <span class="hljs-string">'((\\d{1,3}\\.){3}\\d{1,3}))'</span> + <span class="hljs-comment">// OR ip (v4) address</span>
      <span class="hljs-string">'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'</span> + <span class="hljs-comment">// port and path</span>
      <span class="hljs-string">'(\\?[;&amp;a-z\\d%_.~+=-]*)?'</span> + <span class="hljs-comment">// query string</span>
      <span class="hljs-string">'(\\#[-a-z\\d_]*)?$'</span>, <span class="hljs-comment">// fragment locator</span>
    <span class="hljs-string">'i'</span>
  );
  <span class="hljs-keyword">return</span> pattern.test(str);
}

<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'mailto://freecodecamp.org'</span>)); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'freeCodeCamp'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>Now only the first example which has a valid <code>https:</code> protocol returns <code>true</code>. Note that URL strings with <code>http:</code> work, too.</p>
<h2 id="heading-wrapping-up">Wrapping up!</h2>
<p>In this article, you learned how to check the validity of URLs in JavaScript. You now know the following three methods for doing so.</p>
<ul>
<li><p>How to Use the <code>URL</code> Constructor to Validate URLs</p>
</li>
<li><p>How to Use npm Packages to Validate URLs (<code>is-url</code> and <code>is-http-url</code>)</p>
</li>
<li><p>How to Use Regex to Validate URLs</p>
</li>
</ul>
<p>It's up to you to choose which method you're comfortable working with.</p>
<p>Thanks for reading. And happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Share Links that Anchor to Any Text on a Webpage ]]>
                </title>
                <description>
                    <![CDATA[ Did you know that there's an unofficial draft specification for a feature that would allow arbitrary text to be passed to the fragment (#) of a URL? This would allow users to share links that point to any particular text on a webpage! What's a URI fr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-you-can-share-links-that-anchor-to-any-text-on-a-webpage/</link>
                <guid isPermaLink="false">66d460f433b83c4378a5183f</guid>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Seth Falco ]]>
                </dc:creator>
                <pubDate>Tue, 09 Aug 2022 19:54:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/untitled.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Did you know that there's an <a target="_blank" href="https://wicg.github.io/scroll-to-text-fragment/">unofficial draft</a> specification for a feature that would allow arbitrary text to be passed to the fragment (<code>#</code>) of a URL?</p>
<p>This would allow users to share links that point to any particular text on a webpage!</p>
<h2 id="heading-whats-a-uri-fragment">What's a URI fragment?</h2>
<p>The <a target="_blank" href="https://en.wikipedia.org/wiki/URI_fragment">URI fragment</a> is the optional part at the end of a URL which starts with a hash (<code>#</code>) character. It lets you refer to a specific part of the document you've accessed.</p>
<p>For example, if you visit the following link, you'll automatically scroll to the top of the section you're reading right now!</p>
<p><a class="post-section-overview" href="#heading-whats-a-uri-fragment">What's a URI fragment?</a></p>
<p>Assuming you're consuming this article in the browser, you'll notice the URL changes too. It's now appended with <code>#what-s-a-uri-fragment</code>, which is the ID that the <a target="_blank" href="https://ghost.org/">Ghost CMS</a> assigned to the heading.</p>
<h2 id="heading-whats-changing">What's Changing?</h2>
<p>Before, the primary way to anchor links to part of a page was by specifying the ID of an HTML element in the fragment (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id">source</a>).</p>
<p>This put readers at the whim of the web developer or content writer. If writers didn't provide appropriate IDs, there'd be no way to anchor links to that section.</p>
<p>Some websites or tools provide a non-standard way of handling this, namely highlighting. For example, in <a target="_blank" href="https://readthedocs.org/">Read the Docs</a> you can pass the <code>highlight</code> query parameter to highlight any particular text on the page.</p>
<p>You can try it out in the <a target="_blank" href="https://docs.weblate.org/en/latest/">Weblate documentation</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-186.png" alt="The Weblate documentation open on the Machine Translations page. The highlight query parameters is specified, so all instances of the word &quot;LibreTranslate&quot;, not case-sensitive, are highlighted." width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://docs.weblate.org/en/latest/admin/machine.html?highlight=libretranslate#libretranslate"><em>This is what you see when you specify the</em> <code>highlight</code> query parameter on the Weblate documentation.</a></p>
<p>Text Fragments are a relatively new proposal which extend the usability of URI fragments to query and highlight any arbitrary text as well.</p>
<h2 id="heading-why-would-this-be-useful">Why Would This Be Useful?</h2>
<p>Can you relate to one or more of these scenarios?</p>
<ul>
<li><p>When sourcing information, you can link directly to the quote or content you cited.</p>
</li>
<li><p>As a member of support staff, you can link to and highlight a particular excerpt of the documentation or FAQ for the user.</p>
</li>
<li><p>Text fragments can be used with any arbitrary text document that can't store anchor metadata, such as plaintext or configuration files.</p>
</li>
<li><p>You're a web developer who implemented a custom solution for this, but can now just let the browser handle it for you.</p>
</li>
</ul>
<p>If so, then this might help better attribute content on the web, highlight information your users need, or relieve some maintenance effort for developers.</p>
<h2 id="heading-the-proposal">The Proposal</h2>
<p>You can specify either literal text, or the start and end of a range of text. The spec includes a pseudo-diagram that demonstrates what the syntax looks like:</p>
<pre><code class="lang-plaintext">:~:text=[prefix-,]textStart[,textEnd][,-suffix]

         context  |-------match-----|  context
</code></pre>
<p>Or alternatively, a more digestible version:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Section</td><td>Required</td><td>Description</td><td>Notes</td></tr>
</thead>
<tbody>
<tr>
<td><code>prefix</code></td><td>false</td><td>Value must appear before the text, but won't be highlighted.</td><td>Must end with <code>-</code>.</td></tr>
<tr>
<td><code>textStart</code></td><td>true</td><td>If <code>textEnd</code> is not specified, matches literally, otherwise used in combination with <code>textEnd</code> to match a range.</td><td></td></tr>
<tr>
<td><code>textEnd</code></td><td>false</td><td>Used in combination with <code>textStart</code> to match a range of text.</td><td></td></tr>
<tr>
<td><code>suffix</code></td><td>false</td><td>Value must appear after the text, but won't be highlighted.</td><td>Must start with <code>-</code>.</td></tr>
</tbody>
</table>
</div><p>The sections <code>prefix</code> and <code>suffix</code> are used for context, so if the text you want to match appears multiple times on a page, you can use them to indicate to the browser which instance you want to match.</p>
<p>To provide some examples, let's suppose we open the Web Monetization website which includes the following text.</p>
<blockquote>
<p>A JavaScript browser API that allows the creation of a payment stream from the user agent to the website</p>
<p>— <a target="_blank" href="https://webmonetization.org/">https://webmonetization.org/</a></p>
</blockquote>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Example</td><td>Highlights</td></tr>
</thead>
<tbody>
<tr>
<td><code>:~:text=javascript</code></td><td>JavaScript</td></tr>
<tr>
<td><code>:~:text=api,stream</code></td><td>API that allows the creation of a payment stream</td></tr>
<tr>
<td><code>:~:text=javascript-,browser</code></td><td>browser</td></tr>
<tr>
<td><code>:~:text=a-,javascript,api</code></td><td>JavaScript browser API</td></tr>
<tr>
<td><code>:~:text=that-,allows,stream,-from</code></td><td>allows the creation of a payment stream</td></tr>
</tbody>
</table>
</div><p>For longer excerpts of text, a range is preferred to avoid bloating the URL. Usually, developers will aim to keep the total length of URLs below 2,000~ characters anyway. This avoids potential issues with older user-agents, especially after accounting for the length of the domain and query parameters.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Untitled-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Matrix_(protocol)#:~:text=KDE,client%20Konversation"><em>Here is how highlighting looks on Chromium when you visit a webpage with a text fragment.</em></a></p>
<h3 id="heading-implementation-details">Implementation Details</h3>
<p>From reading the spec, and testing manually in a Chromium browser, here are some of the finer details with querying content in a text fragment.</p>
<ul>
<li><p>The sections are not case-sensitive, and accents are ignored (<a target="_blank" href="https://wicg.github.io/scroll-to-text-fragment/#finding-ranges-in-a-document">source</a>)</p>
</li>
<li><p>All sections match whole words only, so you can't partially match</p>
</li>
<li><p>Only the first match will be highlighted if there are multiple (<a target="_blank" href="https://wicg.github.io/scroll-to-text-fragment/#syntax">source</a>)</p>
</li>
</ul>
<h2 id="heading-compatibility">Compatibility</h2>
<p>Text fragments are available in most Chromium browsers, as this was implemented in <a target="_blank" href="https://chromestatus.com/feature/4733392803332096">Chromium itself in 2020</a>.</p>
<p>Text fragments are not available in Firefox at all yet. Mozilla will hopefully have this implemented in the future – in February 2022 they <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1753933">opened a ticket to track progress</a>.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://caniuse.com/url-scroll-to-text-fragment">https://caniuse.com/url-scroll-to-text-fragment</a></div>
<p> </p>
<h2 id="heading-privacy-and-security">Privacy and Security</h2>
<p>Some concerns have been raised with the specifications, namely that automatically scrolling to parts of the page may reveal certain details about the user.</p>
<p>An interesting thing about URI fragments is that they shouldn't be sent to web servers for processing. URI fragments are intended to be a client-side/user-agent only mechanism to be handled locally by the browser or web application.</p>
<p>To verify this, we can run a small Express server that just logs the URL. We'll see if it includes the fragment:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;

app.get(<span class="hljs-string">'*'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'URL:'</span>, req.url);
   res.status(<span class="hljs-number">204</span>).send();
});

app.listen(port, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Listening on port <span class="hljs-subst">${port}</span>.`</span>); 
});
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Peek-2022-08-06-18-12.gif" alt="Running a webserver and executing curl commands to hit it. When we specify a fragment in the URL in curl, the web server doesn't receive it." width="600" height="400" loading="lazy"></p>
<p><em>The results of each request via curl. The same strings would've printed had I executed the requests in a browser.</em></p>
<p>Some websites take advantage of this to improve privacy and reduce the bandwidth sent to web servers.</p>
<p>For example, if you look at <a target="_blank" href="https://www.typescriptlang.org/play">TypeScript Playground</a>, you'll notice instead of using query parameters or building a short URL, they just encode the TypeScript and store it in the URI fragment.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Untitled.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Observe how the URL includes a URI fragment. It's actually just</em> <code>console.log('Hello, World!');</code> but encoded.</p>
<p>With an implementation like this, you can bookmark or share the link with anyone, and their web server won't know or care about the code. However, any services you use to share the link could, of course, decode and read it.</p>
<p>However, the concern raised with text fragments is that, if a user-agent will automatically scroll down to a given section of a page, while the text fragment wouldn't have been shared with the web server, network requests may've been induced such as loading images on that part of the site. This would allow the web server to derive that you were linked to that section of the page (<a target="_blank" href="https://github.com/WICG/scroll-to-text-fragment/issues/76">source</a>).</p>
<p>Despite these concerns, it appears to me that URI fragments as a whole have been susceptible to this for a long-time, not just text fragments.</p>
<p>Regardless, it's a good thing to keep in mind until browser developers and security researchers give this more thought.</p>
<h2 id="heading-link-to-text-fragment-extension">Link to Text Fragment Extension</h2>
<p>Google has also developed an <a target="_blank" href="https://github.com/GoogleChromeLabs/link-to-text-fragment">extension</a> which provides a UI to link any arbitrary text as a URL.</p>
<p>The extension adds "Copy Link to Selected Text" to the context-menu when you select text and secondary-click on it. You can see it in action on the following video.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Y5DmGqnzvBI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://chrome.google.com/webstore/detail/link-to-text-fragment/pbcodcjpfjdpcineamnnmbkkmkdpajjg">https://chrome.google.com/webstore/detail/link-to-text-fragment/pbcodcjpfjdpcineamnnmbkkmkdpajjg</a></div>
<p> </p>
<p>The extension also ships for Firefox, and polyfills an implementation of text fragments into each webpage, so it'll even scroll to and highlight the matched text too.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://addons.mozilla.org/en-US/firefox/addon/link-to-text-fragment/">https://addons.mozilla.org/en-US/firefox/addon/link-to-text-fragment/</a></div>
<p> </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope this gives more incite on URI fragments as a whole, and especially text fragments.</p>
<p>If you have any ideas for how the specification can be improved, feel free to review the open issues on the browser's and WICG's repositories and provide your thoughts.</p>
<p>I'm eager to see more browsers support this, as it makes the experience of citing, attributing, and linking to content on the web a lot more convenient.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ URL Definition ]]>
                </title>
                <description>
                    <![CDATA[ A URL, or universal resource locator, is the location of an online resource. URLs are sometimes called web addresses. Like street addresses, URLs are unique, and lead to specific online resources. These resources could be HTML or CSS files, API endpo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/url-definition/</link>
                <guid isPermaLink="false">66c36426020f8e9c31066e81</guid>
                
                    <category>
                        <![CDATA[ Tech Terms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 20 Apr 2021 06:16:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/04/timo-wielink-4Zk45jNyQS4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A URL, or universal resource locator, is the location of an online resource.</p>
<p>URLs are sometimes called web addresses. Like street addresses, URLs are unique, and lead to specific online resources. These resources could be HTML or CSS files, API endpoints, and much more.</p>
<p>Here is the URL to freeCodeCamp's homepage: <a target="_blank" href="https://www.freecodecamp.org/">https://www.freecodecamp.org/</a></p>
<p>Tim Berners-Lee created the first specification for the URL in 1994. It built upon the existing domain name structure and added slashes (/) to separate directory and file names like computer file systems.</p>
<p>URLs are made up of several parts, and always include the scheme/protocol, domain name, and path to the file or resource. They may also include the port, parameters, and anchor:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-107.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/mdn-url-all.png" alt="Image" width="600" height="400" loading="lazy">
_Source: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL">What is a URL?</a>_</p>
<p>The domain names of a URL can be broken down further into a subdomain, second-level domain, and top-level domain.</p>
<p>For example, the freeCodeCamp forum is located at <a target="_blank" href="https://forum.freecodecamp.org/">https://forum.freecodecamp.org/</a>.</p>
<p>In this URL, <code>forum</code> is the subdomain, <code>freecodecamp</code> is the second-level domain, and <code>.org</code> is the top-level domain.</p>
<p>The subdomain is a division of the whole domain, and is a bit like a room in a house. Similar to how a bedroom and bathroom serve totally different purposes, different websites or applications can exist on each subdomain. Common subdomains include <code>www</code>, <code>blog</code>, <code>shop</code>, and <code>m</code> for the mobile version of a site.</p>
<p>The second-level domain is the name of your website or resource, and is how people will find it online. Second-level domains are usually the names of people, companies, or organizations.</p>
<p>The top-level domain, or TLD, can give people some information about your company or organization. For example, <code>.com</code> is a generic TLD that can be used for everything from personal sites to online stores. Meanwhile, <code>.org</code> is meant for nonprofit organizations and communities.</p>
<p>These days there are many different TLDs like <code>.dev</code>, <code>.tech</code>, and <code>.rocks</code>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ PHP Get URL – How to Get the Full URL of the Current Page ]]>
                </title>
                <description>
                    <![CDATA[ By Dan Englishby In this PHP-focused article, we will explore how to get the URL of the current page in the PHP programming language.  You may want to get the current page URL for the following reasons: Building internal links Using filters with GET... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/php-get-url-how-to-get-the-full-url-of-the-current-page/</link>
                <guid isPermaLink="false">66d45e03b6b7f664236cbdb8</guid>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 22 Jun 2020 17:37:32 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9a1c740569d1a4ca239c.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dan Englishby</p>
<p>In this PHP-focused article, we will explore how to get the URL of the current page in the PHP programming language. </p>
<p>You may want to get the current page URL for the following reasons:</p>
<ul>
<li>Building internal links</li>
<li>Using filters with GET requests, for example, currentURL.com?myFilterParameter=Food</li>
</ul>
<p>PHP actually stores lots of useful information as users navigate your web application. One of these is, of course, the current URL.</p>
<p>PHP stores these pieces of useful information in its array of super-global variables.</p>
<h3 id="heading-what-are-superglobals">What are Superglobals?</h3>
<blockquote>
<p>Superglobals are already defined variables by the PHP engine which can be used in any kind of scope. They are readily available at any one time.</p>
</blockquote>
<p>There are many of these superglobals, but the one we are interested in is the $_SERVER superglobal.</p>
<h3 id="heading-the-server-superglobal">The $_SERVER Superglobal</h3>
<p>The $_SERVER superglobal variable has many properties that are accessible with an associative style index.  </p>
<p>Some of the values we can access include:</p>
<ul>
<li>HTTP_USER_AGENT</li>
<li>HTTP_HOST</li>
<li>HTTP_ACCEPT_ENCODING</li>
<li>HTTP_ACCEPT</li>
</ul>
<p> You can see more of these indicies in the PHP documentation <a href="https://www.php.net/manual/en/reserved.variables.server.php" target="_blank">here.</a></p>

<h3 id="heading-so-how-do-we-get-the-full-url">So, how do we get the full URL?</h3>
<p>With the above points on superglobals and the <strong>$_SERVER</strong> superglobal in mind, we can go ahead and get the current page's URL. </p>
<p>In the following screenshot, I've rendered a PHP application in a local environment in a page named "home." </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/image-91.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The URL is <strong>http://localhost/home</strong>.</p>
<p>In the code base of this page, I'm going to use the <strong>$_SERVER</strong> variable.</p>
<p>With this variable, we will have to use 2 separate indices to get each part of the current page's URL. The first part will be the host, localhost, and the second part will be the page name, home.</p>
<p>The first index we will use is <strong>HTTP_HOST</strong> - The current web address host, for example localhost, or example.com</p>
<p>The second is <strong>REQUEST_URI</strong> which will give us the part of the URL after the host, so this is anything after localhost or example.com</p>
<p>Let's see this in action:</p>
<pre><code>$currentPageUrl = <span class="hljs-string">'http://'</span> . $_SERVER[<span class="hljs-string">"HTTP_HOST"</span>] . $_SERVER[<span class="hljs-string">"REQUEST_URI"</span>];


echo <span class="hljs-string">"Current page URL "</span> . $currentPageUrl;
</code></pre><h3 id="heading-output">Output</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/image-102.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And that is it - pretty straightforward!</p>
<h2 id="heading-summary">Summary</h2>
<p>The <strong>$_SERVER</strong> superglobal variable stores a lot of vital information for modern day use-cases. As we've discovered in this instance, getting the current page's URL is made simple with the ability to access this specific variable.</p>
<p>It's worth checking out the documentation to see what other indices are available, though, as it's good to have in mind how helpful this variable can be.</p>
<p>I hope you enjoyed this article! If you did, feel free to check out my blog, <a target="_blank" href="https://www.codewall.co.uk/">https://www.codewall.co.uk/</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Unable to Find Images Based on URL in React ]]>
                </title>
                <description>
                    <![CDATA[ If you're new to React and are having trouble accessing images stored locally, you're not alone. Imagine you have your images stored in a directory next to a component like this: /src   /components     - component1     - component2 /img   ]]>
                </description>
                <link>https://www.freecodecamp.org/news/unable-to-find-images-based-on-url-in-react/</link>
                <guid isPermaLink="false">66c363d940438b5931fe09a8</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 Jun 2020 02:19:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9a93740569d1a4ca266c.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're new to React and are having trouble accessing images stored locally, you're not alone.</p>
<p>Imagine you have your images stored in a directory next to a component like this:</p>
<pre><code>/src
  /components
    - component1
    - component2
/img
  - img1
  - img2
</code></pre><p>And you're trying to access the images in the <code>/img</code> directory from <code>component2</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component, useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { render } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>
<span class="hljs-keyword">import</span> { useTransition, animated, config } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-spring"</span>;
<span class="hljs-keyword">import</span> imgArr <span class="hljs-keyword">from</span> <span class="hljs-string">'./images'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'../App.css'</span>;

<span class="hljs-keyword">const</span> Slideshow = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [index, set] = useState(<span class="hljs-number">0</span>)
  <span class="hljs-keyword">const</span> transitions = useTransition(imgArr[index], <span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item.id, {
    <span class="hljs-attr">from</span>: { <span class="hljs-attr">opacity</span>: <span class="hljs-number">0</span> },
    <span class="hljs-attr">enter</span>: {<span class="hljs-attr">opacity</span>: <span class="hljs-number">1</span> },
    <span class="hljs-attr">leave</span>: { <span class="hljs-attr">opacity</span>: <span class="hljs-number">0</span> },
    <span class="hljs-attr">config</span>: config.molasses,
  })
  useEffect(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">void</span> <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> set(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> (state + <span class="hljs-number">1</span>) % <span class="hljs-number">4</span>), <span class="hljs-number">2000</span>), [])
  <span class="hljs-keyword">return</span> transitions.map(<span class="hljs-function">(<span class="hljs-params">{ item, props, key }</span>) =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">animated.div</span>
      <span class="hljs-attr">key</span>=<span class="hljs-string">{key}</span>
      <span class="hljs-attr">className</span>=<span class="hljs-string">"bg"</span>
      <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">...props</span>, <span class="hljs-attr">slideshowContainerStyle</span>}}
    &gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"img"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{require(item.url)}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">animated.div</span>&gt;</span></span>
  ))
}

<span class="hljs-keyword">const</span> slideshowContainerStyle = {
 <span class="hljs-attr">width</span>: <span class="hljs-string">'80%'</span>,
 <span class="hljs-attr">height</span>: <span class="hljs-string">'300px'</span>
}


<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Slideshow;
</code></pre>
<p>You've tried the paths <code>../img/img1.jpg</code> and <code>..img/img1.jpg</code>, but get <code>Error: Cannot find module '&lt;path&gt;'</code> .</p>
<p>So what's going on here?</p>
<h2 id="heading-a-little-about-create-react-app">A little about <code>create-react-app</code></h2>
<p>Like most people, you probably used <code>create-react-app</code> to bootstrap your project.</p>
<p>In that case, using relative paths can be a bit tricky because <code>create-react-app</code> builds the HTML, CSS, and JavaScript files to an output folder:</p>
<pre><code>/public
  - index.html
  - bundle.js
  - style.css
</code></pre><p>There are a number of ways to use images with <code>create-react-app</code>, but one of the easiest is to include your images into <code>/public</code>. When your project is built, <code>/public</code> serves as the root directory.</p>
<p>You can read more about adding images or other assets in the <a target="_blank" href="https://create-react-app.dev/docs/adding-images-fonts-and-files/">Create React App docs</a>.</p>
<h2 id="heading-importing-images">Importing images</h2>
<p>If you took a look at the docs, you'll notice that the code includes <code>import</code> statements to load assets like images and fonts.</p>
<p>Importing is useful when your asset, in this case an image, is in the same directory or near the component that uses it, and won't be used anywhere else. For example, if you have an input component with buttons that use SVGs for thumbs up and thumbs down icons.</p>
<p>A bit advantage of using <code>import</code> is that it will throw an error during build time if there's a typo. This sort of checking helps ensure users won't see a broken image that slipped by.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ HTML URL Encoded Characters Reference ]]>
                </title>
                <description>
                    <![CDATA[ A URL is an address for a website. Just like postal addresses have to follow a specific format to be understood by the postman, URLS have to follow a format to be understood and get you to the right location. There are only certain characters that ar... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/url-encoded-characters-reference/</link>
                <guid isPermaLink="false">66c36428b737bb2ce7073201</guid>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 27 Jan 2020 21:50:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d67740569d1a4ca3792.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A URL is an address for a website. Just like postal addresses have to follow a specific format to be understood by the postman, URLS have to follow a format to be understood and get you to the right location.</p>
<p>There are only certain characters that are allowed in the URL string, alphabetic characters, numerals, and a few characters <code>; , / ? : @ &amp; = + $ - _ . ! ~ * ' ( ) #</code> that can have special meanings.</p>
<h2 id="heading-reserved-characters">Reserved Characters</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.55.13-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-encoding">Encoding</h2>
<p>Any character that is not an alphabetic character, a number, or a reserved character being used needs to be encoded.</p>
<p>URLs use the ASCII (“American Standard Code for Information Interchange”) character-set and so encoding must be to a valid ASCII format.</p>
<p>There are functions in most web languages to do this encoding for you, for example in JavaScript <code>encodeURI()</code> and in PHP <code>rawurlencode()</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.57.33-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.57.53-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.58.06-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.58.18-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.58.32-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.58.43-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.58.57-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.59.07-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.59.18-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.59.27-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.59.46-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-25-at-1.59.55-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-example">Example:</h3>
<pre><code class="lang-js"><span class="hljs-built_in">encodeURI</span>(Free Code Camp);
<span class="hljs-comment">// Free%20Code%20Camp</span>
</code></pre>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What happens when you click on a URL in your browser ]]>
                </title>
                <description>
                    <![CDATA[ By Anchal Nigam In this article, I want my readers to get a picture of a very basic concept of the web world. Previously, I've written articles on the fancy stuff of today’s market, i.e. Angular journey, basics of react, etc. But, today, I want my re... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-happens-when-you-hit-url-in-your-browser/</link>
                <guid isPermaLink="false">66d45da1246e57ac83a2c705</guid>
                
                    <category>
                        <![CDATA[ Browsers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ internet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 30 Jun 2019 08:06:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/browser.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Anchal Nigam</p>
<p>In this article, I want my readers to get a picture of a very basic concept of the web world. Previously, I've written articles on the fancy stuff of today’s market, i.e. <a target="_blank" href="https://www.freecodecamp.org/news/angular-a-journey-into-one-of-the-most-popular-front-end-tools-in-todays-job-market/">Angular journey</a>, <a target="_blank" href="https://www.freecodecamp.org/news/start-your-journey-into-the-world-of-react-by-learning-these-basics-d6e05d3655e3/">basics of react,</a> etc. But, today, I want my readers to get into the journey which they encounter at first when they hit any URL. </p>
<p>As the topic is self explanatory - <strong>when we hit any URL then what happens?</strong> - let’s start!</p>
<p>Before discussing <strong>what happens after hitting the URL</strong>, we must go through what a URL actually is, and what different parts of the URL mean - right? Without wasting any time, let’s understand more about URLs.</p>
<h2 id="heading-url-uniform-resource-locator">URL – Uniform Resource Locator</h2>
<p>If you look into its full form, then it is self explanatory: it has the location of the resources which we want to access. It is an <strong>address of the place</strong> where we want to go to interact with or find information. </p>
<p>Let's look into your daily life. If you want to visit your friend’s house for some work or to get information, you need their address. The same thing goes here in this big web world: we have to give an address of the website which we want to access. The <strong>web site is like the house and the URL is the address.</strong></p>
<h3 id="heading-anatomy-of-a-url">Anatomy of a URL</h3>
<p>Now, we know what a URL is but we still don’t know about the parts of a URL. Let’s go!</p>
<p>Let’s take an example:</p>
<p><a target="_blank" href="https://www.example.com/page1">https://www.example.com/page1</a></p>
<p>Here, the first part is <strong>‘https’</strong>. This basically tells the browser which protocol it should use. It can be <strong>http, https, ftp,</strong> etc. A <strong>protocol</strong> is a <strong>set of rules</strong> that browser use for communication over the network. <strong>'https'</strong> is basically a <strong>secure version</strong>, i.e. information is exchanged in a secure way.</p>
<p>The second part <strong>www.example.com</strong> is a <strong>domain name</strong>. You can relate it to your friend’s house. It is an address of website. We use it to reach to the server (trained computer) that is responsible for serving the information for that website. Wait! You might think, a seconds before I mentioned URL is the address whereas I also mentioned domain name is also address. You may have been confused. Don’t be confused!</p>
<h3 id="heading-difference-between-url-and-domain-name">Difference between URL and Domain Name</h3>
<p>The major difference between both is that the <strong>URL is a complete address</strong>. URL tells about the method through which information should exchange, the path after reaching that website. Whereas the <strong>domain name is part of a URL</strong>. </p>
<p>Let’s take our previous example to better understand. You can say that your friend’s house address is a domain name, whereas the URL not only tells the friend’s house address (domain name) but also how you are going to communicate like talking in a separate room (secure) or in front of everyone (info can get leak). It also tells the path, i.e. at which part of the house you will go after entering into the house. Hence, the domain name is part of the URL. A domain name with more information is a URL. </p>
<p>I hope now you are clear with the URL. Let’s get into the next part.</p>
<h2 id="heading-domain-name">Domain Name</h2>
<p>In the previous part, I explained about domain names, but not in depth. I want you to go into it more. As I told you, the Domain name is the address of the website. It gives a <strong>unique identity</strong> to your <strong>website</strong> in such a huge web world. No two domain names can be the same BUT - Yes! There is ‘but’. This is not the only definition of a domain name. There is another story behind it. Let’s get into that story.</p>
<p>As we know, when we hit any URL or you can say domain name, then that website gets opened with its content. A server (a trained computer) serves it. We also know that every computer has an IP address which is used for communication over the internet. It is an address as its self explaining ‘IP address’. When we <strong>hit</strong> any <strong>URL,</strong> then we are actually <strong>hitting</strong> the <strong>IP address</strong> of the computer which is responsible for serving the website content (hosting). </p>
<p>But, now, you might think what the hell...is everything an address? Why does this domain name exist if the IP address is there? Why can’t we use IP address to get content of the website? </p>
<p>Yes! You can <strong>use IP addresses</strong> to <strong>get content</strong> of the website but really!.. Would you be able to remember each website’s associated IP address? Obviously not! It’s <strong>hard</strong> to <strong>remember the IP address</strong> of every website. That’s why domain names came into the market.</p>
<p>You can relate it to your contact list. You can’t remember every person’s number, but you can remember their name. Same concept applies here as well. You <strong>can’t remember</strong> those scary <strong>IP addresses</strong>, but you can easily <strong>remember</strong> <strong>domain names</strong>. </p>
<p>This huge amount of data is maintained in a database where the domain name with its IP address is stored. A system that stores domain names with its corresponding IP address is known as <strong>DNS (Domain name system)</strong> (I believe you must have heard about it).</p>
<p>I think I have discussed enough basics. Now, get a deep dive into the process of when we hit any URL.</p>
<h2 id="heading-dns-lookup-to-find-ip-address">DNS lookup to find IP address</h2>
<p>After hitting the URL, the first thing that needs to happen is to resolve IP address associated with the domain name. DNS helps in resolving this. <strong>DNS is like a phone book</strong> and <strong>helps us to provide the IP address</strong> that is associated with the domain name just like our phone book gives a mobile number which is associated with the person’s name.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/dns.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is the overview, but there are <strong>four layers</strong> through which this domain name query goes through. Let’s understand the steps: </p>
<ol>
<li><p>After hitting the URL, the <strong>browser cache</strong> is checked. As browser maintains its DNS records for some amount of time for the websites you have visited earlier. Hence, firstly, DNS query runs here to find the IP address associated with the domain name. </p>
</li>
<li><p>The second place where DNS query runs in <strong>OS cache</strong> followed by <strong>router cache</strong>.</p>
</li>
<li><p>If in the above steps, a DNS query does not get resolved, then it takes the help of resolver server. Resolver server is nothing but your ISP (Internet service provider). The query is sent to ISP where DNS query runs in <strong>ISP cache.</strong></p>
<ol start="4">
<li>If in 3rd steps as well, no results found, then request sends to <strong>top or root server</strong> of the DNS hierarchy. There it never happens that it says no results found, but actually it tells, from where this information you can get. If you are searching IP address of the top level domain (.com,.net,.Gov,. org). It tells the resolver server to search <strong>TLD server</strong> (Top level domain).</li>
</ol>
</li>
<li><p>Now, resolver asks TLD server to give IP address of our domain name. TLD stores address information of domain name. It tells the resolver to ask it to <strong>Authoritative Name server.</strong> </p>
</li>
<li><p>The authoritative name server is responsible for knowing everything about the domain name. Finally, resolver (ISP) gets the IP address associated with the domain name and sends it back to the browser.</p>
</li>
</ol>
<p>After getting an IP address, resolver stores it in its cache so that next time, if the same query comes then it does not have to go to all these steps again. It can now provide IP address from their cache. </p>
<p>This is all about the steps that is followed to resolve IP address that is associated with the domain name. Have a look below to better understand:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/dns_resolve.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-tcp-connection-initiates-with-the-server-by-browser">TCP connection initiates with the server by Browser</h2>
<p>Once the <strong>IP address</strong> of the computer (where your website information is there) is <strong>found</strong>, it <strong>initiates connection</strong> with it. To communicate over the network, <strong>internet protocol</strong> is followed. <strong>TCP/IP</strong> is most common protocol. A connection is built between two using a process called <strong>‘TCP 3-way handshake’</strong>. Let’s understand the process in brief:</p>
<ol>
<li><p>A client computer sends a <strong>SYN message</strong> means, whether second computer is open for new connection or not. </p>
</li>
<li><p>Then <strong>another computer</strong>, if open for new connection, it sends <strong>acknowledge message</strong> with SYN message as well. </p>
</li>
<li><p>After this, <strong>first computer</strong> receives its message and acknowledge by <strong>sending</strong> an <strong>ACK message.</strong></p>
</li>
</ol>
<p>To better  understand, look below diagram.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/process.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-communication-starts-request-response-process">Communication Starts (Request Response Process)</h2>
<p>Finally, the connection is built between client and server. Now, they both can communicate with each other and share information. After successful connection, <strong>browser (client)</strong> sends a <strong>request</strong> to a <strong>server</strong> that I want this content. The server knows everything of what response it should send for every request. Hence, the <strong>server responds back.</strong> This response contains every information that you requested like web page, status-code, cache-control, etc. Now, the browser renders the content that has been requested.</p>
<p>That’s it! All the above process happens when we hit any URL. Although this lengthy process takes less than seconds to complete. This is the answer to your question <strong>‘what happens when we hit any URL in a browser?’</strong></p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
