<?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[ Okosa Leonard - 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[ Okosa Leonard - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 23 May 2026 16:26:52 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Okosaleo/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Create Multi-Page Animations Using Framer Motion & React-Router-Dom ]]>
                </title>
                <description>
                    <![CDATA[ Animations are what make plain websites turn into exciting and unforgettable experiences. They give your website a bit of personality and uniqueness and leave the visitor admiring the overall aesthetic. It's a no-brainer that humans love beautiful th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-multi-page-animations-using-framer-motion-and-react-router-dom/</link>
                <guid isPermaLink="false">66d4608c230dff016690584f</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react router ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okosa Leonard ]]>
                </dc:creator>
                <pubDate>Mon, 17 Jun 2024 05:57:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/Green-Abstract-Wavy-Background-Motivational-Quote-Facebook-Post.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Animations are what make plain websites turn into exciting and unforgettable experiences. They give your website a bit of personality and uniqueness and leave the visitor admiring the overall aesthetic.</p>
<p>It's a no-brainer that humans love beautiful things. We all love products that look easy on the eyes.</p>
<p>In this article, we're going to learn how to create animations that wow users with the use of Framer motion and React-Router-Dom.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To be able to follow what we're doing in this article, you should have some knowledge of <a target="_blank" href="https://react.dev/">React</a>, <a target="_blank" href="https://www.framer.com/motion/">Framer motion</a> and <a target="_blank" href="https://reactrouter.com/">React-Router-DOM</a>.</p>
<p>To learn Framer motion better, you can study their documentation.</p>
<p><a target="_blank" href="https://nodejs.org/en/download/package-manager">Node.js</a> should also be installed on your system, and you should have a working code editor. I'll be using <a target="_blank" href="https://code.visualstudio.com/">VS Code</a>.</p>
<h2 id="heading-how-to-set-up-the-project">How to Set Up the Project</h2>
<p>To set up our project we're going to use Vite to set up our React development environment.</p>
<ol>
<li><p>Open the terminal in VScode. You can use Ctrl + backtick(`)</p>
</li>
<li><p>In your terminal, enter the following command:</p>
</li>
</ol>
<pre><code class="lang-plaintext">npm create vite@latest
</code></pre>
<ol start="3">
<li><p>Follow the prompts to name your project and choose your desired framework. In our case, we're using React. This will be a JavaScript project.</p>
</li>
<li><p>Go to your project directory and use <code>npm i</code> in the terminal.</p>
</li>
<li><p>To start your project use <code>npm run dev</code>.</p>
</li>
<li><p>Remember to clean your project by removing the code in App.js and your CSS files in the <code>src</code> folder.</p>
</li>
</ol>
<h2 id="heading-how-to-initialize-framer-motion-and-react-router-dom">How to Initialize Framer Motion and React-Router-Dom</h2>
<ol>
<li>To install Framer-motion in your project open the terminal and enter:</li>
</ol>
<pre><code class="lang-plaintext">npm i framer-motion
</code></pre>
<ol start="2">
<li>To install React-Router-DOM in your project open the terminal and enter:</li>
</ol>
<pre><code class="lang-plaintext">npm i react-router-dom
</code></pre>
<h2 id="heading-how-to-set-up-components-and-basic-routing-with-react-router-dom">How to Set Up Components and Basic Routing with React-Router-DOM</h2>
<p>Let's set up our components and the pages we'll be routing to for this project.</p>
<ol>
<li><p>In <code>src</code>, create a new folder named <code>components</code>.</p>
</li>
<li><p>We'll add four files in this folder named <code>Home.jsx</code>, <code>About.jsx</code>, <code>Projects.jsx</code> and <code>Navbar.jsx</code>.</p>
</li>
<li><p>Inside the first three, we're going to create a React functional component. Change the content of the <code>h1</code> tag in each component:</p>
</li>
</ol>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> Home = <span class="hljs-function">() =&gt;</span> {
 <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
 )
 }

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home
</code></pre>
<ol start="4">
<li>In the Navbar, we need to import <code>Link</code> from React-Router-DOM to create anchor elements. We then need to create a container housing our logo and nav links. The logo will link the points to our index page.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {Link} <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>

<span class="hljs-keyword">const</span> Navbar () =&gt; {
 <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">"nav"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo"</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"nav-link"</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/"</span>&gt;</span>Lennythedev<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">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"nav-links"</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"nav-link"</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/"</span>&gt;</span>Home<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">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"nav-link"</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/"</span>&gt;</span>About<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">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"nav-link"</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/"</span>&gt;</span>Projects<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">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">div</span>&gt;</span></span>
  )
 }
</code></pre>
<ol start="5">
<li>Now let's go to our <code>index.js</code> or <code>main.js</code> file. The goal is to wrap our entire app with <code>BrowserRouter</code> which will enable routing within our application.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App.jsx'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.css'</span>
<span class="hljs-keyword">import</span> { BrowserRouter <span class="hljs-keyword">as</span> Router, Routes, Route } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Router</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/*'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">App</span> /&gt;</span>} /&gt;
      <span class="hljs-tag">&lt;/<span class="hljs-name">Routes</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Router</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
)
</code></pre>
<ol start="6">
<li>Now in <code>App.js</code>, we're going to complete the final step of our configuration. We'll import our components, and some features from React-Router-DOM and render our components. By using <code>useLocation</code> feature from React-Router-DOM, we can set the current location of the routes by setting the key to the current path.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>
<span class="hljs-keyword">import</span> { Routes, Route, useLocation } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> NavBar <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/NavBar'</span>;
<span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Home'</span>;
<span class="hljs-keyword">import</span> Projects <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Projects'</span>;
<span class="hljs-keyword">import</span> About <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/About'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> location = useLocation();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">NavBar</span> /&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">AnimatePresence</span> <span class="hljs-attr">mode</span>=<span class="hljs-string">'wait'</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span> <span class="hljs-attr">location</span>=<span class="hljs-string">{location}</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{location.pathname}</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">Home</span> /&gt;</span>} /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/projects'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Projects</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">'/about'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">About</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">AnimatePresence</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<ol start="7">
<li>Now we can add our styling in <code>App.css</code>:</li>
</ol>
<pre><code class="lang-css">* {
  <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-attribute">color</span>: white;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Fira Sans Condensed"</span>, sans-serif;
}

<span class="hljs-selector-tag">html</span>,
<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Fira Sans Condensed"</span>, sans-serif;
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">0</span>, <span class="hljs-number">162</span>, <span class="hljs-number">255</span>);
}

<span class="hljs-selector-class">.nav</span> {
  <span class="hljs-attribute">position</span>: fixed;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-between;
}

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

<span class="hljs-selector-class">.logo</span>, <span class="hljs-selector-class">.nav-item</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">2em</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">400</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.5vw</span>;
}

<span class="hljs-selector-tag">h1</span>{
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">50%</span>;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">50%</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(-<span class="hljs-number">50%</span>, -<span class="hljs-number">50%</span>);
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">500</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">10vw</span>;
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">text-transform</span>: uppercase;
}

<span class="hljs-selector-tag">a</span> {
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">500</span>;
}
</code></pre>
<ol start="8">
<li>After following all the steps your app should look like this:</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/06/Annotation-2024-06-14-200041.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>styled webpage without animation</em></p>
<h2 id="heading-how-to-create-transitions-using-framer-motion">How to Create Transitions Using Framer Motion</h2>
<p>Finally let's create our animation for transitions between pages.</p>
<ol>
<li><p>Create a file in components named <code>Box.jsx</code> and <code>import motion from framer-motion</code>.</p>
</li>
<li><p>We can then return two divs, with <code>classNames</code> of <code>slide-in</code> and <code>slide-out</code> one for sliding in and another for sliding out.</p>
</li>
<li><p>We insert our animation in these divs with the help of framer-motion:</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { motion } <span class="hljs-keyword">from</span> <span class="hljs-string">"framer-motion"</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">Box</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">div</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">motion.div</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"slide-in"</span>
        <span class="hljs-attr">initial</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">scaleY:</span> <span class="hljs-attr">0</span> }}
        <span class="hljs-attr">animate</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">scaleY:</span> <span class="hljs-attr">0</span> }}
        <span class="hljs-attr">exit</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">scaleY:</span> <span class="hljs-attr">1</span> }}
        <span class="hljs-attr">transition</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">duration:</span> <span class="hljs-attr">1</span>, <span class="hljs-attr">ease:</span> [<span class="hljs-attr">0.22</span>, <span class="hljs-attr">1</span>, <span class="hljs-attr">0.36</span>, <span class="hljs-attr">1</span>] }}
     /&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">motion.div</span>
     <span class="hljs-attr">className</span>=<span class="hljs-string">"slide-out"</span>
        <span class="hljs-attr">initial</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">scaleY:</span> <span class="hljs-attr">1</span> }}
        <span class="hljs-attr">animate</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">scaleY:</span> <span class="hljs-attr">0</span> }}
        <span class="hljs-attr">exit</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">scaleY:</span> <span class="hljs-attr">0</span> }}
        <span class="hljs-attr">transition</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">duration:</span> <span class="hljs-attr">1</span>, <span class="hljs-attr">ease:</span> [<span class="hljs-attr">0.22</span>, <span class="hljs-attr">1</span>, <span class="hljs-attr">0.36</span>, <span class="hljs-attr">1</span>] }}
     /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<ol start="4">
<li>Next, we add our styling in our CSS file for <code>slide-in</code> and <code>slide-out</code> in our App.css</li>
</ol>
<pre><code class="lang-css"><span class="hljs-selector-class">.slide-in</span> {
  <span class="hljs-attribute">position</span>: fixed;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#0f0f0f</span>;
  <span class="hljs-attribute">transform-origin</span>: bottom;
}

<span class="hljs-selector-class">.slide-out</span> {
  <span class="hljs-attribute">position</span>: fixed;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#0f0f0f</span>;
  <span class="hljs-attribute">transform-origin</span>: top;
}
</code></pre>
<ol start="5">
<li>Finally, the last step is to use <code>AnimatePresence</code> from framer-motion in our <code>App.js</code> file and wrap the entire App in <code>AnimatePresence</code> and set the mode as wait. If you want to learn more about a <code>AnimatePresence</code> visit the framer-motion docs.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>
<span class="hljs-keyword">import</span> { Routes, Route, useLocation } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> NavBar <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/NavBar'</span>;
<span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Home'</span>;
<span class="hljs-keyword">import</span> Projects <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Projects'</span>;
<span class="hljs-keyword">import</span> About <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/About'</span>;
<span class="hljs-keyword">import</span> { AnimatePresence } <span class="hljs-keyword">from</span> <span class="hljs-string">'framer-motion'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> location = useLocation();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">NavBar</span> /&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">AnimatePresence</span> <span class="hljs-attr">mode</span>=<span class="hljs-string">'wait'</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span> <span class="hljs-attr">location</span>=<span class="hljs-string">{location}</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{location.pathname}</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">Home</span> /&gt;</span>} /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/projects'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Projects</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">'/about'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">About</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">AnimatePresence</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<ol start="6">
<li>Finally, our work should look the same as the video below:</li>
</ol>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Sb1txpdycpA" 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>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Creating multi-page animations with Framer Motion and React-Router-Dom enhances user experience by providing smooth transitions.</p>
<p>This integration leverages the power of Framer Motion's animation capabilities with React-Router-Dom's routing features, resulting in dynamic, interactive web applications.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use SonarLint to Write Cleaner Code ]]>
                </title>
                <description>
                    <![CDATA[ When you're building a coding project, the better it is, the more fun it'll be to use. And the prouder you'll be of your hard work, right? Also, writing quality and performant code helps your program or website work as expected – which should be ever... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/use-sonarlint-to-write-cleaner-code/</link>
                <guid isPermaLink="false">66d4609233b83c4378a51822</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ workflow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okosa Leonard ]]>
                </dc:creator>
                <pubDate>Thu, 18 Jan 2024 23:58:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/slint.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you're building a coding project, the better it is, the more fun it'll be to use. And the prouder you'll be of your hard work, right?</p>
<p>Also, writing quality and performant code helps your program or website work as expected – which should be every developer's goal.</p>
<p><a target="_blank" href="https://docs.sonarsource.com/sonarcloud/improving/sonarlint/">SonarLint</a> is a tool that helps you make sure your code is top-notch. It's like having a friendly guide who checks your code to see if it's well-written and doesn't have mistakes.</p>
<h2 id="heading-what-is-sonarlint">What is SonarLint?</h2>
<p>SonarLint is an open-source code analysis tool that helps you find and resolve security and code quality problems in your source code as you're writing it. This plugin works with several integrated development environments (IDEs), including well-known ones like IntelliJ IDEA, Eclipse, and Visual Studio.</p>
<p>SonarLint's main purpose is to give you immediate feedback on possible problems with your code, including security flaws, bugs, and other recommended practices for programming. SonarLint analyzes code in the background while you create or change it in your IDE, giving you instant feedback and frequently exposing problems right in the code editor.</p>
<p>SonarLint is a component of the larger SonarQube ecosystem.</p>
<p>In this article, I'll teach you how to use SonarLint to help you write quality code.</p>
<h2 id="heading-why-is-sonarlint-useful">Why is SonarLint Useful?</h2>
<p>Let's imagine that building a website is like constructing a house. You want your house to be safe and well-designed, right? Well, SonarLint is like having a thorough inspector who checks your work as you build, making sure everything is just right.</p>
<p>Here's why SonarLint is important in web development:</p>
<ol>
<li><p><strong>Catch Mistakes Early (Code Quality):</strong> Assuming you were building a staircase, and accidentally put a step in the wrong place, SonarLint is like a smart friend who tells you immediately, "Hey, you might have made a mistake here!" It helps catch small errors in your code before they become big problems.</p>
</li>
<li><p><strong>Follow the Blueprint (Coding Standards):</strong> When building a house, you follow a blueprint to make sure everything fits together. In coding, there are also rules (like a blueprint) on how to write good code. SonarLint helps you stick to these rules, making your code easy to read and work with.</p>
</li>
<li><p><strong>Keep It Secure (Security):</strong> Just like you'd want your house to have good locks on the doors, you'd want your website to be secure. SonarLint checks your code for potential security issues, ensuring there are no "unlocked doors" that could let bad things happen.</p>
</li>
<li><p><strong>Work Together Well (Collaboration):</strong> Imagine that each builder in your team used a different kind of tool. It would be chaos! SonarLint helps your team work together smoothly by making sure everyone follows the same coding standards. This way, everyone can understand and contribute to the project easily.</p>
</li>
<li><p><strong>Save Time and Effort (Efficiency):</strong> Fixing mistakes after the whole house is built would take a lot of time and effort. SonarLint helps you fix issues as you go, saving you from returning and redoing things. It's like having a helpful friend who stops you from making mistakes in the first place.</p>
</li>
<li><p><strong>Learn and Improve (Education):</strong> SonarLint does not only point out mistakes but also explains why they might be a problem. It's like having a coding teacher who helps you understand how to write better code. This way, you learn and become a better developer over time.</p>
</li>
</ol>
<p>So, in the world of web development, SonarLint is your coding buddy, and it makes sure your JavaScript "house" is strong, secure, and well-organized from the ground up. It's a valuable tool in your workflow and helps you create high-quality websites that everyone can enjoy.</p>
<p>But you still may be wondering why you need this tool. You have a debugger already installed in your IDE and it can already track the errors in your environment.</p>
<p>Well, integrating SonarLint complements your debugger by focusing on code quality and security during development.</p>
<p>While a debugger helps to find and fix runtime issues, SonarLint analyzes code in real time, identifies bugs and potential vulnerabilities, and enforces coding standards.</p>
<p>You can also customize and configure coding rules based on your project's specific requirements and coding standards.</p>
<p>This proactive approach enhances overall code quality and ensures cleaner, more maintainable code before it reaches the debugging stage. This leads to fewer errors and smoother development workflows.</p>
<p>Before we get into the details of how to set up and use SonarLint, let's look at what makes code high-quality.</p>
<h2 id="heading-code-quality-metrics">Code Quality Metrics</h2>
<p>Be the best cookbook author! When writing code there are specific guidelines you must follow.</p>
<p>Just like when you're cooking up a new recipe or want to follow a traditional one, you should make sure anyone who reads it can follow along, and that the recipe you wrote down results in a good dish.</p>
<p>In the same sense, when writing code, it's always important to make your code readable so that other developers can understand it easily and so your code works as it's supposed to. Code quality metrics are like measuring how well you followed the recipe.</p>
<p>Here's a breakdown:</p>
<p><strong>Readability (Clarity):</strong> This is similar to making sure your recipe instructions are clear. The code should be easy for others (or future you) to understand.</p>
<p><strong>Maintainability (Ease of Changes):</strong> If you had to change ingredients in your recipe (code), it should be easy to switch things without chaos.</p>
<p><strong>Performance (Speed):</strong> As you'd want your meal ready quickly, efficient code is expected to run fast. Code quality metrics check how fast your code is executed.</p>
<p><strong>Reliability (Consistency):</strong> A good recipe always tastes the same. Similarly, reliable code consistently produces the correct results.</p>
<p><strong>Security (Safety):</strong> Just like checking if ingredients are safe to eat, code quality metrics look for potential dangers in your code that could be exploited.</p>
<p>These should be your goals when writing quality code. And SonarLint can help you accomplish them.</p>
<h2 id="heading-how-to-set-up-sonarlint-and-integrate-with-your-ide">How to Set Up SonarLint and Integrate with Your IDE</h2>
<p>An IDE (Integrated Development Environment) is a software application that helps developers write and debug code more effectively. IDEs include a code editor and compiler or interpreter.</p>
<p>In this article, you'll see how to install SonarLint using VS Code extensions.</p>
<h3 id="heading-how-to-install-sonarlint-with-vs-code">How to Install SonarLint with VS Code</h3>
<p>First, install VS Code or open the application if you've already installed it.</p>
<p>Next, head over to the Extensions tab on VS Code and download the SonarLint extension.</p>
<p>To use the SonarLint extension for JavaScript, TypeScript, or CSS, you should have a minimum version of <code>14.17.0</code> of Node.js installed on your system (especially if you want to use <a target="_blank" href="https://docs.sonarsource.com/sonarlint/vs-code/team-features/connected-mode/">Connected Mode</a> with Sonar Cloud).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/sonar.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Install SonarLint in VS Code</em></p>
<p>Now that you've installed SonarLint, running an analysis on your code should be easy and it should start immediately after you open a new file.</p>
<p>This means SonarLint will start working and catching errors in your code as you write them on your IDE. Now let's look at an example in the next section.</p>
<h3 id="heading-how-to-use-sonarlint-in-your-ide">How to Use SonarLint in Your IDE</h3>
<p>Now let's look at how you can get the best out of SonarLint on your IDE. SonarLint is also a wonderful teacher, helping you better understand how to write clean code and giving you more information about why you have an error.</p>
<p>So instead of scouring the web to figure out what's wrong with your code, SonarLint explains why it has given you an error.</p>
<p>Here's an example of how to use it.</p>
<p>To be able to see the interface where we'll be working, open your terminal on VS Code – you can use Ctrl + backtick (`) to do this. I'm currently working on a project in React.js, and I didn't notice that I have duplicate border property names in my CSS class. Luckily, SonarLint caught this issue.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/sonarlint.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A CSS error caught by SonarLint</em></p>
<p>If you click on the light bulb, you'll see an option to fix the code by deactivating the CSS rule or to be blunt removing the extra border which I have in my CSS class in this instance. There's also another option for opening a description rule so you can understand why you're getting that error.</p>
<p>So SonarLint gives you two options:</p>
<ol>
<li><p>It offers an option that gives you the ability and resources to understand why you have that error with the "Open description of rule".</p>
</li>
<li><p>It offers a solution to the error of the code which it has found.</p>
</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/sonarlint-another.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Options offered by SonarLint to help fix and understand this problem</em></p>
<p>If you click on the open description rule, SonarLint opens another tab in VS Code to help you understand why it has thrown that error and how you can write cleaner/better code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/sonarlint-teacher.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Tab opened by SonarLint in VSCode to help understand the error</em></p>
<p>As you can see, SonarLint is an excellent teacher and your best buddy as you continue to build and work on your IDE.</p>
<p>Another great thing about SonarLint is that it works with multiple programming languages. So whatever programming language you're using, chances are that SonarLint can handle it.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>SonarLint is like having a coding buddy that helps you become a better programmer. As you write code, it's like having a teacher right there with you, pointing out ways to improve.</p>
<p>Imagine having a super-smart friend who does not just spot mistakes but also explains why they're wrong and shows you how to fix them.</p>
<p>Before your code gets to the testing stage, SonarLint checks for mistakes and makes sure your program runs smoothly. It's like having a superpower to catch issues early, saving you time and effort.</p>
<p>But that's not all! SonarLint is also like a security guard for your code. It watches out for any potential weak points that could let bad things happen. By learning from SonarLint, you can write better code and become more aware of keeping your code safe and secure.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Make React Apps SEO-Friendly – A Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ When developing your web applications, you should always consider search engine optimization (SEO) techniques. Many things come into play when you're making sure your web application operates as intended and has an online presence. Search engines suc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-seo-friendly-react-apps/</link>
                <guid isPermaLink="false">66d4608ec7632f8bfbf1e479</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SEO ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okosa Leonard ]]>
                </dc:creator>
                <pubDate>Tue, 09 Jan 2024 15:25:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/How-to-Make-React-Apps-SEO-Friendly-Cover--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When developing your web applications, you should always consider search engine optimization (SEO) techniques. Many things come into play when you're making sure your web application operates as intended and has an online presence.</p>
<p>Search engines such as Google, Bing, and Yahoo serve as the primary medium for users seeking information, services, and products off the internet. An SEO-friendly web app is strategically crafted to align with the algorithms and ranking criteria of the world's most popular search engines.</p>
<p>The objective is clear: to maximize the application's internet visibility, improve its discoverability, and eventually draw in a larger and more focused user base.</p>
<p>There are many benefits of optimizing web apps for search engines. It guarantees increased exposure in search engine results, which puts the application in front of people who are actively looking for relevant material. More exposure results in more organic traffic, which is a more economical and sustainable way to draw visitors than depending on paid advertising.</p>
<p>Let's dive more deeply into why SEO is important for your web applications.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this article, you should have an intermediate level knowledge of React. You should also have beginner level knowledge in Express.js and be confident surfing the web.</p>
<p>You'll need to have a code editor installed – for example VS Code – and create a React app using Vite. To do that, you can enter the following line in your terminal: <code>npm create vite@latest</code>, then follow the prompts. Or you can use this command in your terminal: <code>npx-create-react-app</code> (or with yarn) for MacOS users.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-importance-of-seo-in-your-react-applications">Importance of SEO in Your React Applications.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-seo-challenges-in-react-apps">SEO Challenges in React Apps.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-solutions-to-seo-spa-challenges">Solutions to SEO-SPA Challenges.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-client-side-rendering">What is Client-Side Rendering?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-server-side-rendering">What is Server-Side Rendering?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-server-side-rendering-in-react">How to Implement Server-Side Rendering In React.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-lazy-loading-in-react">How to Implement Lazy Loading in React.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-does-page-load-speed-affect-seo-rankings">How Does Page Load Speed Affect SEO Ranking?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-optimize-images-in-react">How to Optimize Images In React.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tools-for-measuring-image-performance">Tools For Measuring Image Performance.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-incorporate-metadata-for-seo-into-your-react-application">How to Incorporate Metadata for SEO into your React Application.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-for-metadata-in-react">Best Practices For Metadata in React.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-optimize-metadata-with-schema-markup">How to Optimize Metadata with Schema Markup.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-test-and-monitor-your-react-apps-using-seo-tools">Testing Your React App Using SEO tools</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-importance-of-seo-in-your-react-applications">Importance of SEO in Your React Applications</h2>
<p>To make sure that people who need your website or web app are discovering it, search engine optimization (SEO) is crucial.</p>
<p>The following are some reasons why SEO is vital for web applications:</p>
<h3 id="heading-increased-visibility-and-traffic">Increased Visibility and Traffic</h3>
<p>SEO best practices help ensure that your apps are search engine optimized, which makes it easier for consumers to locate them while searching for relevant terms. Improved search engine results result in higher click-through rates, which in turn attract more organic users to the web application.</p>
<h3 id="heading-improvement-in-user-experience">Improvement in User Experience</h3>
<p>SEO techniques frequently concentrate on enhancing website content, navigation, and structure to improve user experience overall. User happiness is significantly impacted by well-optimized online applications, which often feature quicker loading times, responsiveness on mobile devices, and easy navigation.</p>
<h3 id="heading-targeted-marketing">Targeted Marketing</h3>
<p>Web applications can target audience demographics and particular keywords with the aid of SEO. Web apps can draw customers who are actively looking for goods, services, or information they provide by optimizing for certain search queries used by those audiences.</p>
<h3 id="heading-credibility-and-reliability">Credibility and Reliability</h3>
<p>Credibility and reliability often go hand in hand with high search engine ranks. Web applications that rank well in search results are often trusted more by users. So if you have a website that handles sensitive data and offers services that depend on user confidentiality, make sure you implement security measures and user interface features that foster trust.</p>
<p>These are just a few of the many reasons why you should try to make your websites SEO-friendly. Now let's get down to understanding SEO in React-based applications.</p>
<h2 id="heading-seo-challenges-in-react-apps">SEO Challenges in React Apps</h2>
<p>It can be a bit difficult to make single-page applications (SPAs) SEO-friendly. So why is this the case?</p>
<p>Single Page Applications (SPAs) can help deliver a dynamic and seamless user experience, as they load content asynchronously without requiring complete page reloads.</p>
<p>The main SEO obstacle is that dynamic material is rendered using JavaScript, which may be difficult for conventional search engine crawlers to comprehend and index.</p>
<p>The first hurdle is making sure search engines can effectively crawl and index the SPA content. Search engine bots may find it more difficult to correctly index material on SPAs as they frequently load content asynchronously and rely on JavaScript frameworks like Angular or React.</p>
<p>To provide HTML snapshots that search engines can understand and enhance the SPA's visibility in search results, proper implementation of server-side rendering (SSR) or pre-rendering becomes essential.</p>
<h3 id="heading-solutions-to-seo-spa-challenges">Solutions to SEO-SPA Challenges</h3>
<p>There are a couple of ways to handle the SEO challenges that come with SPAs.</p>
<p>Solution number one involves using server-side rendering (SSR) or pre-rendering to create HTML snapshots for search engines.</p>
<p>Solution number two involves handling complicated URL structures to guarantee appropriate indexing and content interpretation.</p>
<p>So now let's discuss how server-side rendering and client-side rendering work and the benefits they bring to your React apps.</p>
<h2 id="heading-what-is-client-side-rendering">What is Client-Side Rendering?</h2>
<p>In web development, client-side rendering (or CSR) is a technique that uses JavaScript to predominantly render web pages on the client side.</p>
<p>In this architecture, the browser runs JavaScript to build and render the content on the client's device dynamically after receiving minimum HTML, CSS, and JavaScript from the server.</p>
<p>In Single Page Applications (SPAs) context, client-side rendering is common. Within a SPA, the application dynamically refreshes the content without requiring a page reload when a user moves between various sections or pages. Because just the data that is required is retrieved from the server and rendering takes place on the client side, this method offers a more seamless and responsive user experience.</p>
<h3 id="heading-problems-with-client-side-rendering">Problems with Client-Side Rendering</h3>
<p>The inability of search engine crawlers to properly digest and comprehend the material is a drawback of client-side rendering, particularly when it comes to SEO. Search engines may not view the completely rendered content because the first HTML delivered by the server is frequently limited, which might affect the SPA's visibility in search results.</p>
<h2 id="heading-what-is-server-side-rendering">What is Server-Side Rendering?</h2>
<p>In web development, server-side rendering (SSR) is a technique that allows the client's browser to receive the completely rendered page after the HTML content has been generated by the server.</p>
<p>This is different from Client-Side Rendering where the client device renders the content using JavaScript and sends minimal basic HTML to the browser.</p>
<h3 id="heading-how-does-server-side-rendering-help-with-seo">How does Server-Side Rendering help with SEO?</h3>
<p>SSR is essential for solving CSR-related issues in the context of SEO, especially for Single Page Applications (SPAs). In contrast to CSR, SSR benefits SEO in the following ways:</p>
<h4 id="heading-crawling-through-search-engines">Crawling through search engines:</h4>
<p>Usually, search engine crawlers use HTML analysis to index material. Search engines may find it difficult to comprehend and index material while using CSR, as a large portion of the content rendering process takes place on the client side.</p>
<p>SSR helps make sure that the search engine receives a completely rendered HTML page from the server, which facilitates correct content indexing by crawlers.</p>
<h4 id="heading-initial-page-load">Initial page load:</h4>
<p>In contrast to CSR, SSR offers a quicker first-page load. Delays may occur in CSR because the client device must download the bare minimum of HTML, run JavaScript, and then render the content.</p>
<p>By pre-rendering the HTML, SSR improves user experience by cutting down on the amount of time it takes for consumers to see the initial content.</p>
<h4 id="heading-seo-efficiency">SEO efficiency</h4>
<p>Indexable and readily available material is frequently given priority by search engines. By ensuring that the server delivers a fully formed HTML page to the client, SSR enhances SEO performance and conforms to search engine standards.</p>
<p>Server-side rendering helps SEO performance astronomically. By giving search engines fully rendered HTML material, improving crawling and indexing capabilities, and eventually improving visibility in search engine results, it overcomes the drawbacks of client-side rendering.</p>
<p>Now, let's talk about how to use server-side rendering in React.</p>
<h2 id="heading-how-to-implement-server-side-rendering-in-react">How to Implement Server-Side Rendering in React</h2>
<p>If you're a front-end engineer/ developer, we're going to go a little bit off track here. The use case I'll display involves a little bit of backend knowledge with <code>express.js</code> and <code>node.js</code>, but I'll walk you through it.</p>
<p>By setting up your application to create the initial HTML on the server side instead of only depending on client-side rendering, you can implement Server-Side Rendering (SSR) in React.</p>
<p>Server-side rendering is made easier by React with the ReactDOMServer package. Let's walk through the general process for enabling SSR in a React application.</p>
<h3 id="heading-step-1-server-setup">Step 1: Server Setup.</h3>
<p>To manage incoming requests and render React components on the server side, you'll need to set up a server using <code>Node.js</code> and <code>Express.js</code>.</p>
<p>Then, install all required packages, including <code>react</code>, <code>express</code>, <code>react-dom</code>, and any other dependencies. You'll need to create all the necessary files for housing different components and features like your <code>app.js</code> and <code>server.js</code>. And finally, make sure Node is installed on your system.</p>
<h3 id="heading-step-2-establish-a-server-side-access-point">Step 2: Establish a Server-Side Access Point.</h3>
<p>Now you'll need to make a file with the name server.js or another similar entry point for the server.</p>
<p>Bring in the required modules, such as the <code>ReactDOMServer</code> module and your React components. Here are the commands to do that:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOMServer <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>; <span class="hljs-comment">// Import your main React component</span>
</code></pre>
<h3 id="heading-step-3-set-up-your-port-for-your-project">Step 3: Set up Your Port for Your Project.</h3>
<p>Establish a port to access your project in your server.js by inputting the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">3000</span>;
app.listen(PORT)
</code></pre>
<p>Now you'll be able to access this project on <code>localhost:3000</code> in your web browser if you have Node installed on your system.</p>
<h3 id="heading-step-4-establish-routes">Step 4: Establish Routes.</h3>
<p>As I mentioned above, if you're not a full-stack developer some of these concepts may be a little hard to grasp. To help you out, I'll go over what routes are before moving on:</p>
<h4 id="heading-what-are-routes">What are routes?</h4>
<p>The paths or URLs that users can access within an application are referred to as routes. They are a key concept in web application development, as they help specify how the program reacts to various user requests. They're also important when deciding which view or material to display depending on the particular URL or path requested.</p>
<p>Routes are frequently linked to certain URL pathways. For example in a blogging application, the route "/posts" may point to a page with a list of blog entries, but the route "/about" may point to a page with information about the blog.</p>
<p>Now that you understand a bit more about what routes are, let's continue with our example of server-side rendering in React.</p>
<p>In your <code>server.js</code> file, define routes and indicate which React components should be rendered for each one:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> app = express();

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> html = ReactDOMServer.renderToString(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);
  res.send(html);
});

<span class="hljs-comment">// Add as many routes as you need</span>
</code></pre>
<h3 id="heading-step-5-handling-static-assets">Step 5: Handling Static Assets.</h3>
<p>Serving static files like HTML, CSS, pictures, and client-side JavaScript straight to clients without requiring any server processing is known as "static file handling" in Express.js. Without this, the server won't be able to properly serve your files to the browser.</p>
<p>Now to ensure that static assets such as CSS, image files, font files, and so on are served properly, you'll need to configure your server to handle these files.</p>
<p>To do this, make sure you create a folder with your naming preferences and add the files in there. Then use the code below to let Express.js know that static files are located in that specific folder.</p>
<p>So in <code>server.js</code> write the following code:</p>
<pre><code class="lang-javascript">app.use(express.static(<span class="hljs-string">'public'</span>)); <span class="hljs-comment">// Replace 'public' with your static assets directory</span>
</code></pre>
<h3 id="heading-step-6-run-your-server">Step 6: Run Your Server.</h3>
<p>Start your server to see SSR in action by running <code>node server.js</code> in the terminal.</p>
<p>Go to <a target="_blank" href="http://localhost:3000">http://localhost:3000</a> (or the port you set) to see you're server-side rendered React application.</p>
<p>Note: Depending on your project's requirements and structure, the implementation may differ from this basic outline. For more intricate apps, Next.js and other similar frameworks offer a higher-level abstraction for React server-side rendering.</p>
<p>Now let's look at other features that help with SEO when using React.</p>
<h2 id="heading-how-to-implement-lazy-loading-in-react">How to Implement Lazy Loading in React</h2>
<h3 id="heading-what-is-lazy-loading">What is Lazy Loading?</h3>
<p>In React, lazy loading is the practice of waiting to load specific components or assets until they are truly required. When working with big and complicated apps, where loading all components at once may cause slower initial page loads, this may greatly enhance the speed of a React application.</p>
<p>Lazy loading in a React context is frequently connected to the <code>Suspense</code> component and the <code>React.lazy</code> method. With the help of this feature, you can load components asynchronously, which means that they are only retrieved and displayed when the screen is ready to display them.</p>
<p>I've written a whole article on using React suspense and lazy loading, You can <a target="_blank" href="https://www.freecodecamp.org/news/react-suspense/">check it out here</a> – but we're still going to talk about these key concepts a bit here.</p>
<h3 id="heading-step-1-how-to-use-reactlazy">Step 1: How to Use <code>React.lazy</code></h3>
<p><code>React.lazy</code> makes code splitting possible. Code splitting is dividing your JavaScript code into multiple files so they can be loaded separately by the browser. This enables effective component imports, which reduces the initial bundle size by loading components only when needed.</p>
<p>Asynchronously retrieving and rendering components enhances efficiency. It's also especially helpful in big applications with complex user interfaces to reduce initial load times.</p>
<p>You may sluggishly load a component using the <code>React.lazy</code> method. A function that yields a dynamic <code>import()</code> statement is required. Here's the code:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> MyLazyComponent = React.lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LeoComponent'</span>));
</code></pre>
<h3 id="heading-step-2-how-to-use-suspense">Step 2: How to use <code>Suspense</code></h3>
<p><code>Suspense</code> is a React component used for handling asynchronous operations in components. It lets you "suspend" rendering until a resource, such as data or a component, is ready. This enhances the user experience and simplifies the handling of asynchronous tasks in React applications.</p>
<p>The lazy-loaded component is wrapped in the <code>Suspense</code> component. It enables you to provide some fallback content (like a loading spinner) that appears while the component that is lazy-loaded loads. Here's the code for this:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> MyLazyComponent = React.lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LeoComponent'</span>));

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyLazyComponentWrapper</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">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">MyLazyComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>
  );
}
</code></pre>
<p>Combining lazy loading with code splitting is a method that divides a huge JavaScript bundle into smaller, easier-to-manage chunks. Code splitting speeds up an application's initial load time by ensuring that only the code required for the current view is loaded.</p>
<p>When boosting the speed of apps with several routes or views, lazy loading is especially helpful. You may minimize the initial payload and enhance user experience overall—especially for users with slower network connections—by loading components only when necessary.</p>
<p>It's important to note that only React versions 16.6 and later enable lazy loading. Lazy loading greatly enhances initial page load time, so now let's talk about how page load speed affects SEO rankings.</p>
<h3 id="heading-how-does-page-load-speed-affect-seo-rankings">How Does Page Load Speed Affect SEO Rankings?</h3>
<p>Google in particular takes into account a website's speed and functionality when determining its ranking.</p>
<p>Let's talk about some ways that page load speed affects search engine rankings:</p>
<h4 id="heading-ux-or-user-experience">UX, or user experience</h4>
<p>Giving people a great experience is something Google takes very seriously. Pages that load slowly might provide users with a bad experience, which raises bounce rates and decreases user happiness.</p>
<p>Faster page loads lead to a better user experience (UX), which in turn can boost SEO results since search engines reward user-satisfied websites.</p>
<h4 id="heading-bounce-rates">Bounce rates</h4>
<p>Pages that load slowly frequently have higher bounce rates (that is, the number of times visitors leaves a website rapidly). Search engines are alerted by high bounce rates when users are not happy with the experience or content.</p>
<p>Reduced bounce rates may be interpreted by search engines as a sign of interesting and relevant content, which might improve SEO rankings.</p>
<h4 id="heading-crawl-budget">Crawl budget</h4>
<p>Every website has a crawl budget that search engine bots use to decide how frequently and how many pages to explore. Pages that load slowly use up more crawl budget, which might result in a website's indexing being incomplete.</p>
<p>Increased website exposure in search results is a result of faster page loads, which allow search engine bots to efficiently crawl and index more pages within the crawl budget allotted.</p>
<h4 id="heading-mobile-responsiveness">Mobile responsiveness</h4>
<p>Google now uses the mobile version of a website for ranking, known as "mobile-first indexing." One of the most crucial aspects of mobile-first indexing is page load speed on mobile devices.</p>
<p>Mobile-friendly or responsive websites are more likely to rank well in search results overall and have faster loading on mobile pages.</p>
<h4 id="heading-core-web-vitals">Core web vitals</h4>
<p>Google released a collection of performance indicators called Core Web Vitals, which includes First Input Delay (FID), Cumulative Layout Shift (CLS), and Largest Contentful Paint (LCP). These measurements concentrate on elements related to interaction and page load speed.</p>
<p>Google gives websites that meet or surpass the Core Web Vitals requirements a higher priority and these sites may see an increase in search ranks.</p>
<p>These are ways in which page load speed affects search ranking. Let's talk about more ways to improve SEO in your React application.</p>
<h2 id="heading-how-to-optimize-images-in-react">How to Optimize Images in React</h2>
<p>An essential component of SEO is image optimization which greatly improves user experience and boosts search engine rankings.</p>
<p>Faster website loads are a result of optimized images, and SEO algorithms take this into account. Websites with fast-loading pages are given preference by search engines like Google because they improve user experience and lower bounce rates.</p>
<p>You'll need to specify image dimensions, choose suitable file formats (WebP offers superior compression), and compress pictures without sacrificing quality. These techniques lower the size of picture files, which speeds up downloads and enhances the overall performance of websites.</p>
<h3 id="heading-image-optimization-techniques-in-react">Image Optimization Techniques in React</h3>
<h4 id="heading-compress-images">Compress images</h4>
<p>You can use image compression methods to shrink files without sacrificing much quality. This quickens the loading of pages, which is important for SEO. Compression is made simple by several online resources and picture editing programs.</p>
<p>There are several resources on the web you can use to compress images for your React application, but I recommend using <a target="_blank" href="https://tinypng.com/">TinyPNG</a>. It's a free resource for compressing WebP, PNG, and JPEGs – so you can just head over to their website to try it out.</p>
<h4 id="heading-choose-appropriate-file-formats">Choose appropriate file formats</h4>
<p>Select the right file format based on the content and use case. JPEG is suitable for photographs, while PNG is ideal for images with transparency. WebP is an emerging format known for its excellent compression and quality.</p>
<h4 id="heading-make-images-responsive">Make images responsive</h4>
<p>Implement responsive image techniques, delivering different image sizes based on the user's device and screen size. This prevents unnecessary loading of large images on smaller screens, enhancing mobile performance.</p>
<p>A technique for making images responsive is putting the <code>max-width</code> CSS property at 100% and ensuring that images scale down proportionally based on the width of their container. Let's give an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ResponsiveImg = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Leo's React Component<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">"Img-container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span>
          <span class="hljs-attr">src</span>=<span class="hljs-string">"/images/Leo-image.jpg"</span>
          <span class="hljs-attr">alt</span>=<span class="hljs-string">"My Image"</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"responsive-image"</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>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ResponsiveImage;
</code></pre>
<p>Then in your CSS, you can define the styles for the responsive image:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.Img-container</span> {
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto; <span class="hljs-comment">/* Center the image */</span>
}

<span class="hljs-selector-class">.responsive-image</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: auto;
  <span class="hljs-attribute">display</span>: block; <span class="hljs-comment">/* Remove extra space below inline images */</span>
}
</code></pre>
<h4 id="heading-use-lazy-loading">Use lazy loading</h4>
<p>Aim to load pictures only when the user's viewport is going to include them by using lazy loading. By gradually loading graphics as the user scrolls, this method saves bandwidth and speeds up initial page loads.</p>
<p>Let's give an example of using lazy loading for images. Look at the code below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { lazy, Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-comment">// Create a lazy-loaded component for the image</span>
<span class="hljs-keyword">const</span> LazyImg = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LennyImage'</span>));

<span class="hljs-comment">// Placeholder while the image is loading</span>
<span class="hljs-keyword">const</span> LoadingPlaceholder = <span class="hljs-function">() =&gt;</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-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Your React App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {/* Use Suspense to handle the lazy-loaded component */}
      <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">LoadingPlaceholder</span> /&gt;</span>}&gt;
        {/* Render the lazy-loaded image component */}
        <span class="hljs-tag">&lt;<span class="hljs-name">LazyImg</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"path/to/your/image.jpg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Lazy-loaded Image"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In this use case:</p>
<ol>
<li><p>First, we created a lazy-loaded component <code>LazyImg</code> using the <code>lazy</code> function, which dynamically imports the component when it's needed.</p>
</li>
<li><p>We defined a <code>LoadingPlaceholder</code> component to render while the image is loading. Simply put, if the image isn't ready to be displayed, this component is shown in its place. This is shown using the <code>fallback</code> prop of the <code>Suspense</code> component.</p>
</li>
<li><p>Inside the <code>App</code> component, we used the <code>Suspense</code> component to wrap the lazy-loaded <code>LazyImg</code> component. The <code>fallback</code> prop specifies what to render while the image is being loaded.</p>
</li>
<li><p>The <code>src</code> and <code>alt</code> props are passed to the lazy-loaded image component. The actual image loading is handled by the <code>LazyImg</code> component.</p>
</li>
</ol>
<h4 id="heading-employ-sprite-images">Employ sprite images</h4>
<p>This is a technique in web development where multiple images are merged into a single image file. This single image file is known as a sprite sheet and can then be used to display different parts of the image at different times, reducing the number of server requests and improving performance.</p>
<p>In your React app, you can consolidate several little pictures, such as buttons or icons, into a single image sprite. As a result, there are fewer server queries, which shorten load times and enhance website functionality.</p>
<h4 id="heading-turn-on-browser-caching">Turn on browser caching</h4>
<p>Configure picture caching in your browser so that users may save locally cached copies. When a browser obtains pictures from its local cache instead of the server, subsequent visits to the same page load quickly.</p>
<p>Let's go over the steps you need to follow to implement browser caching in React.</p>
<p>First, you'll have to use Express once again. To do this you need to configure the server to include appropriate caching headers.</p>
<p><strong>Step 1:</strong> Make sure you have Express.js installed in your project. If you do not, install it by opening your terminal with Ctrl + backtick (<code>) and inputting the command</code> npm install express`.</p>
<p><strong>Step 2:</strong> Create an Express.js server file (for example, <code>server.js</code>) to serve your React application, serve static files, and handle routes.</p>
<pre><code class="lang-javascript"><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> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// Serve static files, including images, from the 'public' directory</span>
app.use(express.static(path.join(__dirname, <span class="hljs-string">'public'</span>), { <span class="hljs-attr">maxAge</span>: <span class="hljs-string">'30d'</span> }));

<span class="hljs-comment">// Handle other routes (e.g., React routes)</span>
app.get(<span class="hljs-string">'*'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.sendFile(path.join(__dirname, <span class="hljs-string">'public'</span>, <span class="hljs-string">'index.html'</span>));
});

<span class="hljs-comment">// Start the server</span>
<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">3000</span>;
app.listen(PORT, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on http://localhost:<span class="hljs-subst">${PORT}</span>`</span>);
});
</code></pre>
<p>Using the <code>maxAge</code> option is set to <code>'30d'</code>, this indicates that the browser should cache the images for 30 days. Adjust this value based on your specific requirements.</p>
<p><strong>Step 3:</strong> Place your images in the 'public' directory. For instance, if you have an image named <code>Leo-Image.jpg</code>, put it in the 'public/images' directory.</p>
<p><strong>Step 4:</strong> Include the image in your React component and reference with relative paths making sure you rendered the image correctly.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> LeosComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Leo React Component<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/images/Leo-Image.jpg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Leo Image"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> LeosComponent;
</code></pre>
<p><strong>Step 5:</strong> Examine network requests using the browser developer tools to make sure the caching headers are set appropriately. Search for HTTP headers that indicate the caching strategy, such as Expires and Cache-Control.</p>
<p>This setup should guarantee that photos are stored in the browser cache for the allotted time, improving efficiency by lowering the number of needless downloads of images on subsequent visits. Adapt the other variables and the cache time to the needs of your application.</p>
<p>Incorporating these image optimization techniques not only boosts website performance but also positively impacts SEO rankings. By prioritizing efficient image delivery and enhancing user experience, websites can achieve faster load times, reduced bounce rates, and improved visibility in search engine results.</p>
<p>Now, let's discuss the tools we can use to measure image performance.</p>
<h3 id="heading-tools-for-measuring-image-performance">Tools for Measuring Image Performance</h3>
<p>There are several tools to measure image performance on your web apps. We'll be discussing six of these tools that help web developers understand how images affect load time and user experience:</p>
<ol>
<li><p>Google's <a target="_blank" href="https://developers.google.com/speed/docs/insights/v5/about">PageSpeed insights</a>: With a tool called PageSpeed Insights, Google assesses a webpage's content and offers suggestions for improvement. It offers comprehensive guidance on picture optimization and creates a performance score by evaluating several factors. You can learn a lot about how your images impact load time with the aid of this tool. To use Google PageSpeed Insights click on this link <a target="_blank" href="https://pagespeed.web.dev/">https://pagespeed.web.dev/</a> and input your website's name it's as simple as that once you do that a group of numerous metrics will be displayed where you can analyze your website's performance.</p>
</li>
<li><p><a target="_blank" href="https://github.com/GoogleChrome/lighthouse">Lighthouse</a>: Lighthouse is an automatic, open-source tool for raising the caliber of webpages. With its integration into the Chrome Developer Tools, it offers thorough audits that incorporate metrics related to image speed. Lighthouse provides information on how to enhance overall page performance and optimize pictures.</p>
</li>
<li><p><a target="_blank" href="https://www.webpagetest.org/">WebPageTest</a>: WebPageTest gives you comprehensive insights into a range of performance measures, including image optimization, and lets you test a website's functionality from several locations. It provides waterfall charts that illustrate the order in which resources load and point out areas in need of development. To use WebPageTest head to <a target="_blank" href="https://www.webpagetest.org/">https://www.webpagetest.org/</a> and input your website's URL to get an analysis of your website's performance.</p>
</li>
<li><p><a target="_blank" href="https://tools.pingdom.com/">Pingdom tools</a>: The website speed test provided by Pingdom Tools sheds light on several performance metrics, including the time it takes for images to load. It offers a performance grade and indicates areas that could require optimization work. Pingdom tools also offer testing from different locations. To use Pingdom tools, head to <a target="_blank" href="https://tools.pingdom.com/">https://tools.pingdom.com/</a> and insert your website's URL.</p>
</li>
<li><p><a target="_blank" href="https://imageoptim.com/mac">ImageOptim</a>: ImageOptim is a macOS desktop application that allows you to resize and optimize photos manually. It uses many optimization algorithms and supports a range of picture formats without sacrificing quality. To use ImageOptim head over to <a target="_blank" href="https://imageoptim.com/mac">https://imageoptim.com/mac</a> and download the application.</p>
</li>
<li><p><a target="_blank" href="https://tinypng.com/">TinyPNG</a> and <a target="_blank" href="https://tinyjpg.com/">TinyJPG</a>: We've talked about TinyPNG before. You can optimize and reduce the size of PNG and JPEG photos with TinyPNG and TinyJPG, two web programs. These programs minimize file sizes without sacrificing visual quality by using cutting-edge compression algorithms.</p>
</li>
</ol>
<h4 id="heading-how-to-run-lighthouse-on-chrome-developer-tools">How to run Lighthouse on Chrome Developer Tools:</h4>
<ol>
<li><p>Make sure you have Google Chrome Installed.</p>
</li>
<li><p>Once you have Chrome installed, open Chrome and run the command <code>Ctrl+shift+i</code></p>
</li>
<li><p>Chrome developer tools should open up. Navigate to the lighthouse section, if you do not see it immediately refer to the image below to navigate to the Lighthouse tool. Analyze the URL you inserted in your search bar to generate a Lighthouse report.</p>
</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/chrome-dev-tools-navigation-image.png" alt="Chrome developer tools navigation" width="600" height="400" loading="lazy"></p>
<ol start="4">
<li>There you'll see any problems associated with your webpage including image performance.</li>
</ol>
<p>With these metrics, you can understand and learn SEO problems your React app might be facing and tackle them.</p>
<p>Let's continue our journey of improving SEO in your React application by talking about how to use metadata in your React application.</p>
<h2 id="heading-how-to-incorporate-metadata-for-seo-into-your-react-application">How to Incorporate Metadata for SEO into Your React Application</h2>
<h3 id="heading-what-is-metadata-in-react-and-how-does-it-affect-seo">What is Metadata in React and How Does it Affect SEO?</h3>
<p>Metadata in React refers to the information and additional contexts that are passed into a web page about the content.</p>
<p>Metadata gives search engines information about the content of a website or web application and enhances how pages are indexed and shown in search results. It's crucial to improving search engine optimization (SEO).</p>
<p>In React apps, common metadata types include:</p>
<ol>
<li><p>Title Tags: In an HTML document, the <code>&lt;title&gt;</code> element gives the title of the page, which is shown on the browser tab and in search engine results. Title tags in React apps may be dynamically updated based on the content being presented.</p>
</li>
<li><p>Meta Descriptions: The description property of the <code>&lt;meta&gt;</code> element offers a brief overview of the page content. Well-written meta descriptions can improve search result click-through rates and provide search engines with a better sense of the page's relevancy.</p>
</li>
</ol>
<p>In HTML meta descriptions are included in the <code>&lt;head&gt;</code> section of a webpage. Let's have some examples of how meta descriptions can be implemented using HTML:</p>
<ol>
<li>Basic Meta Description:</li>
</ol>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"Your brief and compelling description goes here."</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
</code></pre>
<ol start="2">
<li>Using React Helmet in React.js:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Helmet } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-helmet'</span>;

<span class="hljs-keyword">const</span> LeoComponent = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Helmet</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"Your meta description goes here."</span> /&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Helmet</span>&gt;</span>
            {/* Rest of your component */}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> LeoComponent;
</code></pre>
<ol start="3">
<li>Open Graph (OG) Tags: Open Graph tags, which are widely used on sites such as Facebook, allow React developers to manage how the material looks when shared on social media. They contain information such as the title, description, picture, and content type.</li>
</ol>
<p>Here's an example of using Open Graph Tags in React:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Helmet } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-helmet'</span>;

<span class="hljs-keyword">const</span> LeoComponent = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Data for Open Graph tags</span>
    <span class="hljs-keyword">const</span> ogData = {
        <span class="hljs-attr">title</span>: <span class="hljs-string">'Your Page Title'</span>,
        <span class="hljs-attr">description</span>: <span class="hljs-string">'Description of your page content.'</span>,
        <span class="hljs-attr">url</span>: <span class="hljs-string">'https://www.yourwebsite.com'</span>,
        <span class="hljs-attr">image</span>: <span class="hljs-string">'https://www.yourwebsite.com/og-image.jpg'</span>,
        <span class="hljs-attr">siteName</span>: <span class="hljs-string">'Your Website Name'</span>,
    };

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Helmet</span>&gt;</span>
                {/* Open Graph Meta Tags */}
                <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"og:title"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{ogData.title}</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"og:description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{ogData.description}</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"og:url"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{ogData.url}</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"og:image"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{ogData.image}</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"og:site_name"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{ogData.siteName}</span> /&gt;</span>
                {/* You can add more Open Graph tags as needed */}

                {/* Other standard meta tags */}
                <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{ogData.description}</span> /&gt;</span>
                {/* Other meta tags as needed */}
            <span class="hljs-tag">&lt;/<span class="hljs-name">Helmet</span>&gt;</span>
            {/* Rest of your component */}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> LeoComponent;
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>og:title</code>: Specifies the title of your page.</p>
</li>
<li><p><code>og:description</code>: Specifies the description of your page content.</p>
</li>
<li><p><code>og:url</code>: Specifies the canonical URL of your page.</p>
</li>
<li><p><code>og:image</code>: Specifies the URL of an image representing your page. This is often used as a preview image when shared on social media.</p>
</li>
<li><p><code>og:site_name</code>: Specifies the name of your website.</p>
</li>
</ul>
<p>Feel free to customize the values in the <code>ogData</code> object according to your specific page content and requirements. Additionally, you can include other Open Graph tags as needed for your particular use case.</p>
<ol start="4">
<li>Canonical Tags: When several URLs point to similar or identical information, <code>&lt;link&gt;</code> tags with the <code>rel="canonical"</code> property help prevent duplicate content concerns by designating the preferred URL. So in simple terms canonical tags are HTML tags that help search engines understand the preferred version of a webpage when multiple versions with similar content exist.</li>
</ol>
<p>Here's an example of a canonical tag in React.js using React Helmet:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Helmet } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-helmet'</span>;

<span class="hljs-keyword">const</span> LeoComponent = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Canonical URL for the page</span>
    <span class="hljs-keyword">const</span> canonicalUrl = <span class="hljs-string">'https://www.yourwebsite.com/your-page'</span>;

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Helmet</span>&gt;</span>
                {/* Canonical Tag */}
                <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"canonical"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">{canonicalUrl}</span> /&gt;</span>

                {/* Other standard meta tags */}
                <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"Description of your page content."</span> /&gt;</span>
                {/* Other meta tags as needed */}
            <span class="hljs-tag">&lt;/<span class="hljs-name">Helmet</span>&gt;</span>
            {/* Rest of your component */}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> LeoComponent;
</code></pre>
<p>In this example, the <code>link</code> tag with the attribute <code>rel="canonical"</code> is used to specify the canonical URL for the page. The <code>href</code> attribute contains the preferred URL that search engines should consider as the authoritative version.</p>
<p>It's crucial to set the canonical tag on all versions of a page with similar content to indicate the preferred version. This helps search engines consolidate the SEO value and avoid confusion about which version to index. Adjust the <code>canonicalUrl</code> variable according to your specific page URLs.</p>
<p>So metadata has an impact on SEO because of its capacity to influence search engine ranks, click-through rates, and user engagement.</p>
<p>Metadata that is well-optimized gives a clear and succinct description of the page's content, increasing the likelihood that it will be revealed in relevant search searches. Also, correct and interesting information encourages visitors to click on search results, which improves a React application's overall SEO performance.</p>
<h3 id="heading-best-practices-for-metadata-in-react">Best Practices for Metadata in React</h3>
<p>Constructing strong and efficient metadata in React, incorporating structured data, and using a schema markup are all very important procedures in search engine optimization.</p>
<p>These actions greatly improve the way content is presented and located in search engine results pages (SERPs). They also help search engines understand the context of a web page.</p>
<p>Here are some ways to improve metadata in your React application:</p>
<h4 id="heading-dynamically-set-title-tags">Dynamically set title tags</h4>
<p>Use React's capability to dynamically set title tags in response to the content being presented. Write clear, pertinent titles that appropriately sum up the information on the page.</p>
<h4 id="heading-optimized-meta-descriptions">Optimized meta descriptions</h4>
<p>Write meta descriptions that, in no more than the suggested 150–160 characters, succinctly summarize the content of the page. Incorporate pertinent keywords to enhance your presence in search results.</p>
<h4 id="heading-use-of-strategic-keywords">Use of strategic keywords</h4>
<p>Include crucial keywords in metadata in a way that makes sense for the content of the page. Steer clear of keyword stuffing and make sure the metadata appropriately summarizes the content on the page.</p>
<h4 id="heading-responsive-meta-tags">Responsive meta tags</h4>
<p>Use responsive meta tags to make sure that the content appears best and consistently on different kinds of devices. This is preferred by search engines and essential for a smooth user experience.<br>Open Graph(OG) tags:</p>
<h4 id="heading-use-og-tags">Use OG tags</h4>
<p>Use OG tags to manage the way material shows up when shared on social media. This improves the way links are displayed visually on social media sites like Facebook, Twitter, and LinkedIn.</p>
<h3 id="heading-how-to-optimize-metadata-with-schema-markup">How to Optimize MetaData with Schema Markup</h3>
<h4 id="heading-what-is-schema-markup">What is Schema Markup?</h4>
<p>Schema markup can also be called structured data. This is code you add to your web pages to help search engines such as Google, Bing, Yahoo, and so on to better understand your webpage content. It's a way to provide extra information about your content so that search engines can show it more effectively in search results.</p>
<p>For example, if you have a recipe on your website, using schema markup allows you to specify details like the ingredients, cooking time, and nutrition information. When someone searches for a recipe, search engines can use this marked-up information to display rich snippets, showing not just the title and meta description but also key details directly in the search results.</p>
<p>Let's look at some examples of using schema markup in our React apps.</p>
<h4 id="heading-employ-the-json-ld-format">Employ the JSON-LD format</h4>
<p>JSON-LD stands for JavaScript Object Notation for Linked Data. It's a lightweight data-interchange format designed to be easy for humans to read and write and easy for machines to parse and generate.</p>
<p>JSON-LD is also a way to structure data to make it understandable for search engines, web crawlers, and other applications.</p>
<p>In the case of our recipe website example from above, let's look at how we can implement JSON-LD in React.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> RecipePage = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Define the recipe details</span>
  <span class="hljs-keyword">const</span> recipe = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Delicious Chocolate Cake'</span>,
    <span class="hljs-attr">description</span>: <span class="hljs-string">'A mouthwatering chocolate cake recipe.'</span>,
    <span class="hljs-attr">recipeIngredient</span>: [
      <span class="hljs-string">'2 cups all-purpose flour'</span>,
      <span class="hljs-string">'1 cup cocoa powder'</span>,
      <span class="hljs-string">'1 cup sugar'</span>,
      <span class="hljs-string">'1 cup butter'</span>,
      <span class="hljs-string">'4 eggs'</span>,
    ],
    <span class="hljs-attr">cookTime</span>: <span class="hljs-string">'PT45M'</span>,
    <span class="hljs-attr">nutrition</span>: {
      <span class="hljs-string">'@type'</span>: <span class="hljs-string">'NutritionInformation'</span>,
      <span class="hljs-attr">calories</span>: <span class="hljs-string">'350 calories per serving'</span>,
      <span class="hljs-attr">servingSize</span>: <span class="hljs-string">'1 slice'</span>,
    },
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{recipe.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{recipe.description}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      {/* Render other recipe content here */}

      {/* Add JSON-LD script for schema markup */}
      <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"application/ld+json"</span>&gt;</span><span class="javascript">
        {<span class="hljs-built_in">JSON</span>.stringify({
          <span class="hljs-string">'@context'</span>: <span class="hljs-string">'https://schema.org'</span>,
          <span class="hljs-string">'@type'</span>: <span class="hljs-string">'Recipe'</span>,
          ...recipe,
        })}
      </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> RecipePage;
</code></pre>
<p>We've developed a RecipePage component in this React example, which renders the recipe data. Within the component, we use a</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use React Suspense to Improve your React Projects ]]>
                </title>
                <description>
                    <![CDATA[ React's ecosystem is always growing, and it seems like there are always new features and enhancements to make development more effective and user-friendly. React Suspense is one such feature that has become quite popular among React devs. In this gui... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-suspense/</link>
                <guid isPermaLink="false">66d46090f855545810e934bb</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okosa Leonard ]]>
                </dc:creator>
                <pubDate>Thu, 16 Nov 2023 17:04:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/pexels-pixabay-289323.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React's ecosystem is always growing, and it seems like there are always new features and enhancements to make development more effective and user-friendly.</p>
<p>React Suspense is one such feature that has become quite popular among React devs.</p>
<p>In this guide, you'll learn all about React Suspense and examine its features, use cases, and potential to transform your web applications.</p>
<h2 id="heading-what-is-react-suspense">What is React Suspense?</h2>
<p>React suspense is a new feature released in React.js version 16.6. With this new feature, components may pause rendering while they wait for an asynchronous process to finish, like separating code or retrieving data.</p>
<p>Suspense was created to make it easier for developers to create apps that have improved loading indications and a more cohesive user experience. It makes it possible to halt component tree rendering until specific criteria are satisfied, which makes it easier for developers to work with asynchronous data.</p>
<h3 id="heading-a-problem-that-loading-states-face-in-react">A Problem That Loading States Face in React</h3>
<p>Managing loading states in React was a little trickier prior to React Suspense. Developers had to implement the loading mechanism using third-party frameworks like Redux or Mobx, conditional rendering, or state management. This frequently resulted in complicated, error-prone code.</p>
<p>This problem was solved by React Suspense, which offers a more sophisticated and integrated method of managing asynchronous actions and loading states.</p>
<h2 id="heading-key-concepts-and-features-of-react-suspense">Key Concepts and Features of React Suspense</h2>
<p>Let's talk about some concepts and features to help you understand React Suspense and how it works.</p>
<h3 id="heading-1-suspense-component">1) Suspense Component</h3>
<p>An essential element of React Suspense is the Suspense component. It lets you declare how to handle fallback content while asynchronous actions are pending and encapsulate any portion of your component tree.</p>
<pre><code class="lang-jsx">&lt;Suspense fallback={<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">LeoFallback</span> /&gt;</span></span>}&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">LeoComponent</span> /&gt;</span></span>
&lt;/Suspense&gt;
</code></pre>
<p>In this use case, if the <code>LeoComponent</code> is not ready, React will display the <code>LeoFallback</code> component instead.</p>
<h3 id="heading-2-using-reactlazy-or-lazy">2) Using <code>React.lazy()</code> or <code>lazy()</code></h3>
<p>React has a dynamic import mechanism called <code>lazy()</code> that lets you load components in a lazy manner.</p>
<p>Basically, lazy loading refers to the requirement that a component or portion of code will load only when it's needed. This functionality, which was first included in React 16.6, is frequently used in conjunction with React Suspense to enhance web application speed by loading components only when needed.</p>
<p>This is very helpful for minimizing your application's loading speed and lowering the initial bundle size.</p>
<p>Now we'll investigate <code>lazy()</code> in further depth and learn how it works.</p>
<h4 id="heading-basic-syntax-of-lazy">Basic Syntax of <code>lazy()</code></h4>
<p>To use <code>lazy()</code>, you have to follow these steps:</p>
<p>First, import the <code>Suspense</code> components from React, as well as any components you intend to load lazily.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
</code></pre>
<p>Then use <code>lazy()</code> to define a dynamic import. For the component you wish to load slowly, this function accepts an argument that is a function that produces a dynamic import statement.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> LeoComponent = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LeoComponent'</span>));
</code></pre>
<p>In this use case, the <code>LeoComponent</code> will be loaded lazily when it's needed. The dynamic <code>import()</code> statement specifies the path to the component you want to import.</p>
<p>Next, enclose the element you wish to load lazily in a Suspense element. You may designate a backup component to show while the lazy-loaded component is being retrieved by using the Suspense component.</p>
<pre><code class="lang-jsx"><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">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">LeoComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, while the <code>LeoComponent</code> is being fetched, the fallback component will be displayed, indicating that the content is loading.</p>
<h4 id="heading-advantages-of-reactlazy">Advantages of <code>React.lazy()</code></h4>
<ol>
<li><p>Enhanced speed: By selectively loading the components needed for the current view and not loading all of the components at once, lazy loading of components can enhance the speed of the application.</p>
</li>
<li><p>Improved User Experience: You may improve the user experience by informing users that the application is actively loading material by utilizing Suspense to display a loading indication.</p>
</li>
<li><p>Code Splitting: One of <code>lazy()</code>'s main advantages is that it makes code splitting possible. The process of code splitting involves breaking up the code of your application into smaller, on-demand bundles. This minimizes the initial bundle size and quickens your application's loading time.</p>
</li>
</ol>
<p>With <code>lazy()</code>, you can do code splitting and lazy loading of components in your React apps. This is a great feature. It is a useful tool for streamlining your web applications' efficiency and loading times, improving user experience by loading components only when needed.</p>
<p>It has restrictions and certain concerns, but when utilized properly, it may be a useful tool in your toolset for React development.</p>
<h3 id="heading-3-error-boundaries">3) Error Boundaries</h3>
<p>React components known as error boundaries have the ability to detect and manage faults inside their subtree. Because they can gently manage any problems that arise while waiting for asynchronous data, they are essential for dealing with suspense.</p>
<pre><code class="lang-jsx"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ErrorBoundary</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  componentDidCatch(error, info) {
    <span class="hljs-comment">// Handle the error</span>
  }

  render() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.props.children;
  }
}
</code></pre>
<h3 id="heading-4-what-is-concurrent-rendering">4) What is Concurrent Rendering?</h3>
<p>React Suspense was introduced as part of Concurrent Mode, which is an experimental set of features in React. Later on, concurrent rendering was introduced.</p>
<p>Concurrent rendering enables the execution of numerous tasks at once, improving the responsiveness and efficiency of React apps. It is a component of Concurrent Mode, a trial-and-error collection of features designed to overcome some of the drawbacks of conventional React rendering.</p>
<p>Ensuring that the user interface stays fluid and responsive even when React is handling complicated rendering or other asynchronous operations is the core objective of concurrent rendering.</p>
<h2 id="heading-how-does-react-suspense-work">How Does React Suspense Work?</h2>
<p>When using React Suspense with asynchronous operations, it follows these steps:</p>
<ol>
<li><p>After React loads, a component tree is rendered.</p>
</li>
<li><p>React looks to see whether any of its child components are in a suspended state when it comes across a Suspense component.</p>
</li>
<li><p>React will display the given fallback UI until the data is ready, if a child component is awaiting data (for example, as a result of a <code>lazy()</code> import or a data fetch).</p>
</li>
<li><p>React smoothly transitions to rendering the real content once the data is available.</p>
</li>
</ol>
<p>Because this procedure is automated, handling asynchronous actions without coding sophisticated logic is significantly easier for developers.</p>
<h2 id="heading-use-cases-for-react-suspense">Use Cases for React Suspense</h2>
<p>React Suspense is a flexible tool for your toolbox that may be used in a variety of scenarios, which include:</p>
<h3 id="heading-1-data-fetching">1. Data Fetching</h3>
<p>React Suspense's data fetching feature makes managing asynchronous data loading in your React apps easier. React Suspense allows you to postpone rendering until the data is available, enhancing user experience by offering fallback content or loading indications.</p>
<p>I'll give an example using a fake API to show how to retrieve data using React Suspense.</p>
<p>Here's how to use React Suspense to manage data loading, assuming you're using a framework like React Query or Relay for data fetching:</p>
<h4 id="heading-establish-error-boundary-and-react-suspense">Establish Error Boundary and React Suspense</h4>
<p>To capture any failures during data retrieving, you must first set up an error boundary and a React Suspense component. Here's how to make a custom <code>ErrorBoundary</code> component in react for data fetching:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ErrorBoundary</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  producer(props) {
    unique(props);
    <span class="hljs-built_in">this</span>.state = { <span class="hljs-attr">hasError</span>: <span class="hljs-literal">false</span> };
  }

  <span class="hljs-keyword">static</span> getDerivedStateFromError(error) {
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">hasError</span>: <span class="hljs-literal">true</span> };
  }

  render() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.state.hasError) {
      <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error: Something is wrong!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.props.children;
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ErrorBoundary;
</code></pre>
<h4 id="heading-use-react-query-to-fetch-data">Use React Query to Fetch Data</h4>
<p>If you're using React Query to retrieve data, you can make a component that uses <code>useQuery</code> to retrieve data and wrap it in <code>Suspense</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { useQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-query'</span>;
<span class="hljs-keyword">import</span> ErrorBoundary <span class="hljs-keyword">from</span> <span class="hljs-string">'./ErrorBoundary'</span>;

<span class="hljs-comment">// Define your data-fetching function</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> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
  <span class="hljs-keyword">if</span> (!response.ok) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
  }
  <span class="hljs-keyword">return</span> response.json();
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DataFetching</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { data, isLoading, isError } = useQuery(<span class="hljs-string">'data'</span>, fetchData);

  <span class="hljs-keyword">if</span> (isLoading) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">2000</span>)); <span class="hljs-comment">// Simulate loading delay</span>
  }

  <span class="hljs-keyword">if</span> (isError) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Error while fetching data'</span>);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Fetching data with React Suspense<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{data}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<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">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Leo's App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ErrorBoundary</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">React.Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">DataFetchingComponent</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">React.Suspense</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ErrorBoundary</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In this example, we fetch data using React Query's <code>useQuery</code> hook. To display the loading indicator, we <code>throw in new Promise</code> to mimic a loading delay if the data is still loading ( <code>isLoading is true</code> ). We throw an error so that the error boundary can catch it if there is a problem.</p>
<p>You can provide a backup component to display while loading by enclosing the <code>DataFetching</code> component in <code>Suspense</code>. It's a straightforward "Loading..." message in this instance.</p>
<p>You'll also want to ensure that the error handling, loading indications, and data fetching function are all customized according to your unique data-fetching needs.</p>
<p>This example shows how React Suspense makes state management and data fetching easier, leading to a more organized and understandable codebase.</p>
<p>These are examples of Suspense being used in a data fetching scenario in React.</p>
<h3 id="heading-2-lazy-loading-in-react-suspense">2. Lazy Loading in React Suspense</h3>
<p>Loading components of your application only when needed (lazy loading, also known as code splitting) can lower the size of your initial bundle and speed up the loading of your React application.</p>
<p>You can use <code>React.lazy()</code> in conjunction with React <code>Suspense</code> to easily include lazy loading into your application.</p>
<p>Here are the steps to implement lazy loading with React suspense:</p>
<p>First, import React Suspense from React:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
</code></pre>
<p>Next, create a lazy loaded component in your React app. To construct a component that loads slowly, use the <code>React.lazy()</code> method. Provide an arrow function to dynamically import the component.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> LennyComponent = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LennyComponent'</span>));
</code></pre>
<p>Then wrap your component with a <code>Suspense</code>. Wrap Suspense around the sluggish part. While the lazy component is loading, you may designate a loading indication or fallback component to be shown.</p>
<pre><code class="lang-jsx"><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">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Leo's App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">LennyComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>The component can be used like any other component in your React application.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LennyComponent</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">div</span>&gt;</span>This component is lazily loaded.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p>To finish building your application, you must use a development server and a tool like Webpack to build and serve your application in order to ensure that code splitting functions as intended. Your code will be automatically divided into pieces using Webpack for lazy loading.</p>
<p>This setup will minimize the initial bundle size and speed up the loading of your React application by only loading the <code>LazyComponent</code> when needed. While the component is being retrieved, users will see the loading indication (in this example, "Loading..."). The component loads and is rendered in the application with ease.</p>
<h3 id="heading-3-better-user-experiences">3. Better User Experiences</h3>
<p>React Suspense can be employed to ensure a smooth user experience by showing loading indicators or fallback content during data loading. This reduces the perceived loading time for people who are using your React application.</p>
<p>For example, let's say you have a component that fetches data from an API using <code>fetch</code> and you want to display a loading spinner while the data is being fetched. Here's a basic example using React Suspense:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-comment">// A component that fetches data</span>
<span class="hljs-keyword">const</span> fetchApiData = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">'Data loaded!'</span>);
    }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Simulating a 2-second delay for data fetching</span>
  });
};

<span class="hljs-comment">// A component that uses Suspense to handle asynchronous data fetching</span>
<span class="hljs-keyword">const</span> DataComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> apidata = fetchApiData(); <span class="hljs-comment">// This can be any async function, like an API call</span>

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{apiData}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
};

<span class="hljs-comment">// Wrapping the component with Suspense</span>
<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">LoadingSpinner</span> /&gt;</span>}&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">DataComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>
  );
};

<span class="hljs-comment">// A simple loading spinner component</span>
<span class="hljs-keyword">const</span> LoadingSpinner = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
};
</code></pre>
<p>In this instance:</p>
<p>The <code>fetchApiData</code> method is used by the <code>DataComponent</code> component to get data. Keep in mind that while <code>fetchApiData</code> is really a straightforward function that returns a promise, it may actually be an API call in practical applications.</p>
<p>The Suspense component, which requires a fallback argument, encapsulates the App component. One component that will be displayed while the asynchronous operation is running is the fallback prop. It's the <code>LoadingSpinner</code> component in this instance.</p>
<p>React Suspense will take care of the asynchronous data fetching automatically when the <code>DataComponent</code> is rendered. The <code>LoadingSpinner</code> component will render if the data is not yet accessible. After the data is retrieved, the user interface is updated.</p>
<p>This method eliminates the need for manual loading state management, making for a more seamless user experience. This code is straightforward and React Suspense works efficiently here.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>React Suspense is a major addition to the React ecosystem. It provides a simpler, integrated method of managing asynchronous actions and loading states. You can use it to design apps that offer quicker loading times, more efficient data fetching, and better user experiences by utilizing <code>Suspense</code>, <code>React.lazy()</code>, and error boundaries.</p>
<p>It's critical to comprehend the capabilities, restrictions, and best practices of any strong instrument. Concurrent Mode and React Suspense have the power to revolutionize web application development and improve user experience even more. But as the React ecosystem continues to grow, it's imperative to keep up with the most recent advancements and industry best practices.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Cypress for End-to-End Testing Your React Apps ]]>
                </title>
                <description>
                    <![CDATA[ React is a popular framework for building web applications. It's is one of the best options for frontend engineering because of its declarative approach to user interface design and component-based architecture. But it can be difficult to make sure y... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cypress-for-end-to-end-testing-react-apps/</link>
                <guid isPermaLink="false">66d4608affe6b1f641b5fa4f</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Testing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okosa Leonard ]]>
                </dc:creator>
                <pubDate>Wed, 01 Nov 2023 22:45:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/1_PfsGOHgjLPh3EFOkxCRmjw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React is a popular framework for building web applications. It's is one of the best options for frontend engineering because of its declarative approach to user interface design and component-based architecture.</p>
<p>But it can be difficult to make sure your React application functions as intended in various different scenarios.</p>
<p>Cypress is an end-to-end testing framework that you can use to test your React apps. And in this tutorial, I'll explain how to create efficient end-to-end tests for your web application using Cypress and React.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-cypress">What is Cypress?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-your-environment">How to Set Up Your Environment</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-write-your-first-cypress-test">How to Write Your First Cypress Test</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-interact-with-react-components">How to Interact with React Components</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cypress-queries">Cypress Queries</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cypress-assertions">Cypress Assertions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cypress-actions">Cypress Actions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-organize-and-run-your-cypress-tests">How to Organize and Run Your Cypress Tests</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-plugins">Plugins</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-describe-blocks">Describe Blocks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-custom-commands">Custom Commands</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cypress-dashboard">Cypress Dashboard</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-debug-your-code-with-cypress">How to Debug Your Code with Cypress</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-continuous-integration">Continuous Integration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-what-is-cypress">What is Cypress?</h2>
<p>Cypress is a straightforward open-source end-to-end testing framework designed for modern web development. It's based on JavaScript.</p>
<p>The tool operates within the browser, which sets it apart from other testing tools like Selenium. The concise, uncomplicated API that Cypress provides for interacting with your application makes it easy to create and manage tests.</p>
<p>You can create and manage tests that mimic user interactions with Cypress. You can also examine your web application for expected behavior and troubleshoot any concerns that arise.</p>
<h2 id="heading-how-to-set-up-your-environment">How to Set Up Your Environment</h2>
<p>Before we begin writing tests, you'll want to set up your environment. You must have Node.js and npm (Node Package Manager) installed in order to use Cypress with your React application.</p>
<p>You can visit <a target="_blank" href="https://nodejs.org/en/">https://nodejs.org/en/</a> to download to install Node.js on your computer if it isn't already installed. To get started using Cyprus after installing Node, you can follow these steps:</p>
<h3 id="heading-1-create-a-react-application">1) Create a React Application</h3>
<p>We'll utilize Vite to develop our React application, as it helps us quickly and efficiently create web apps.</p>
<p>To get started, create a React app on Vite by entering the following code in your console:</p>
<pre><code class="lang-js">npm create vite@latest
</code></pre>
<p>Vite will ask you to give your project a name. Choose whatever name you like.</p>
<p>Following that, Vite will give you the choice of framework. Just make sure you select React for this lesson.</p>
<p>It'll then ask you to select between TypeScript and JavaScript when you select React. Pick JavaScript.</p>
<p>Then go to your project directory and choose your project.</p>
<p>Finally, type <code>npm install</code> after that, and then <code>npm start dev</code> to launch your project.</p>
<p>Your project will be hosted by Vite at <code>http://localhost:5173/</code>. To view your project in a browser, click the link that's provided.</p>
<h3 id="heading-2-install-cypress">2) Install cypress</h3>
<p>You can install Cypress in your project by using this code <code>install cypress –-save-dev</code> in your terminal. This code installs Cypress in your React application.</p>
<h3 id="heading-3-initialize-cypress">3) Initialize Cypress</h3>
<p>Run <code>npx Cypress open</code> from the directory of your React project. This command should launch Cypress Test Runner, a graphical tool for creating and managing tests. You will now have two alternatives for automated testing:</p>
<ul>
<li><p>End-to-End Testing: End-to-end testing involves a browser using an automated tool like Cypress, so you can make tests consisting of functions like pressing buttons, typing in inputs, and so on. This helps make sure everything’s working perfectly.</p>
</li>
<li><p>Component Testing: This involves testing individual components instead of the entire React application.</p>
</li>
</ul>
<h4 id="heading-what-is-the-cypress-test-runner">What is the Cypress Test Runner?</h4>
<p>The test runner opens up once you pass in <code>npx cypress open</code>. It is a graphical tool for creating and managing tests, it also allows you to write and execute your test cases in Cypress.</p>
<p>After selecting what type of testing you want to do, the next section of the test runner helps you specify what script you want to execute, and gives you the option to select the browser you want to use and validate your tests as expected.</p>
<h3 id="heading-4-folder-structure">4) Folder Structure</h3>
<p>Cypress will automatically save its test files and configurations inside of your project in a subfolder named <code>cypress</code>.</p>
<h2 id="heading-how-to-write-your-first-cypress-test">How to Write Your First Cypress Test</h2>
<p>We'll use JavaScript to write our Cypress tests which are executed within the browser. Here's how to create your React application's first test.</p>
<p>Suppose we wish to check to see if the Document Object Model (DOM) displays our h2 element. To accomplish this using Cypress, take the following actions:</p>
<p><strong>Step 1</strong>: In your Cypress folder, go to the e2e file and there you’ll see a line of code similar to this:</p>
<pre><code class="lang-javascript">describe(<span class="hljs-string">'template spec'</span>, <span class="hljs-function">() =&gt;</span> {
    it(<span class="hljs-string">'passes'</span>, <span class="hljs-function">() =&gt;</span> {
        cy.visit(<span class="hljs-string">'https://example.cypress.io'</span>)
    })
    })
</code></pre>
<p><strong>Step 2</strong>: Now, in <code>cy.visit</code>, update the default http address to your React app's address (<a target="_blank" href="http://localhost:5173/">http://localhost:5173/</a>, if you recall).</p>
<p><strong>Step 3</strong>: We wish to check to see if the DOM has our h2 element. Navigate to the element you wish to test and add <code>data-testid</code> as an attribute to accomplish this. Next, assign a name to the attribute. Example: <code>&lt;h2 data-testid="cypress-h1"&gt; Leo Website &lt;/h2&gt;</code>.</p>
<p><strong>Step 4</strong>: Make a space and add this piece of code to your cypress folder to see if the attribute exists.</p>
<pre><code class="lang-js">cy.get(‘[data-testid=”cypress-header”]’).should(“exists”):
</code></pre>
<p>Since Cypress is configured to execute tests upon save, as soon as you save anything in your code editor, the test ought to instantly start in Cypress.</p>
<h2 id="heading-how-to-interact-with-react-components">How to Interact With React Components</h2>
<p>You'll want to be familiar with the vast array of commands used to imitate user interactions in order to write more insightful tests.</p>
<p>With its extensive command set for interacting with and testing online elements, Cypress is designed specifically for webpages and web applications.</p>
<p>To imitate user interactions and assert certain behaviors of the application, test scripts employ these instructions. Because Cypress maintains a promise chain on your behalf, you can chain commands together. Until the chain breaks and an error occurs, each command yields a "subject" to the following command.</p>
<p>Cypress commands can be classified into the following groups: queries, assertions, actions, and others.</p>
<h3 id="heading-cypress-queries">Cypress Queries</h3>
<p>These are Cypress commands that retrieve your application's current status. They retry as necessary to ensure that the DOM element or other data they offer is constantly current. They return a subject for additional commands to act upon or assert.</p>
<p>Here are some ways you can organize and run tests:</p>
<h4 id="heading-using-the-children-method">Using the <code>.children()</code> method</h4>
<p>To choose and work with a parent element's direct child elements in Cypress, use the <code>.children()</code> method. It enables you to access particular child elements of a given parent element by navigating the DOM tree.</p>
<p>Here are some examples of how to use <code>.children()</code> in Cypress:</p>
<p>Example 1: Assuming you have this sort HTML structure in your <code>jsx</code> file:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"parent-element"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child"</span>&gt;</span>Child 1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child"</span>&gt;</span>Child 2<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child"</span>&gt;</span>Child 3<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>To choose and work with the child elements inside the <code>.parent</code> element, use the <code>.children()</code> function like this:</p>
<pre><code class="lang-javascript">cy.get(<span class="hljs-string">'.parent'</span>).children(<span class="hljs-string">'.child'</span>).should(<span class="hljs-string">'have.length'</span>, <span class="hljs-number">3</span>);

<span class="hljs-comment">// Click on the second child element</span>
cy.get(<span class="hljs-string">'.parent'</span>).children(<span class="hljs-string">'.child'</span>).eq(<span class="hljs-number">1</span>).click();
</code></pre>
<p>Example 2: you can perform a whole range of tasks using <code>.children()</code> combined with other Cypress functions. You can, for instance, recognize certain child objects and define their properties:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Ensure that the first child element contains the text "Child 1"</span>
cy.get(<span class="hljs-string">'.parent'</span>).children(<span class="hljs-string">'.child'</span>).first().should(<span class="hljs-string">'contain'</span>, <span class="hljs-string">'Child 1'</span>);

<span class="hljs-comment">// Verify that all child elements have a specific class</span>
cy.get(<span class="hljs-string">'.parent'</span>).children(<span class="hljs-string">'.child'</span>).each(<span class="hljs-function">(<span class="hljs-params">$child</span>) =&gt;</span> {
  cy.wrap($child).should(<span class="hljs-string">'have.class'</span>, <span class="hljs-string">'child'</span>);
});
</code></pre>
<p>Example 3: Many Cypress instructions may be chained together to perform more complex interactions. Using <code>.children()</code>, you can select the parent element, select its child elements, and then operate with the child elements as demonstrated by this example:</p>
<pre><code class="lang-javascript">cy.get(<span class="hljs-string">'.parent'</span>)
  .children(<span class="hljs-string">'.child'</span>)
  .first()
  .click()
  .next()
  .type(<span class="hljs-string">'I'</span>m Leo<span class="hljs-string">');</span>
</code></pre>
<p>To interact with the next child element in this example, we first pick the <code>.parent</code> element, then use <code>.children('.child')</code> to select its child elements, click on the first child element, and then chain more instructions to type "I'm Leo."</p>
<p>These examples show you how to pick and work with child items inside of a parent element in Cypress using the <code>.children()</code> function. Depending on your unique HTML structure, you can modify the CSS selector inside <code>.children()</code> to match the child elements you wish to target.</p>
<p>Now you should have an have an idea of how <code>.children()</code> works and how you can use queries as a type of Cypress command. There are more query commands but you can always refer to the documentation on <a target="_blank" href="https://www.freecodecamp.org/news/p/ee697448-b73d-43dd-85de-d31f1e1005c6/cypress.io">cypress.io</a> to learn more on them.</p>
<h4 id="heading-using-the-cyget-command">Using the cy.get() command</h4>
<p><code>cy.get()</code> is a fundamental command in the Cypress framework. You use it to choose and perform actions on DOM elements inside a web application, including those created using React.</p>
<p>To choose one or more DOM elements from your React application for testing, use the <code>cy.get()</code> command. It lets you pick elements with CSS selectors or other Cypress-compatible methods.</p>
<p>The fundamental syntax of <code>cy.get()</code> is <code>cy.get(selector)</code>.</p>
<p><code>selector</code> is an instance of a CSS selector. There are alternative ways for choosing components based on attributes like ID, class name, or data.</p>
<p>Suppose you have a React component like this:</p>
<pre><code class="lang-javascript">&lt;button data-testid=<span class="hljs-string">"Leo-button"</span>&gt;Click&lt;/button&gt;
</code></pre>
<p>You can use <code>cy.get()</code> to select the button element:</p>
<pre><code class="lang-javascript">cy.get(‘[data-testid=”Leo-button”]’);
</code></pre>
<p><code>cy.get('#Leo-button')</code> in this case chooses the button element with ID "Leo-button."</p>
<h3 id="heading-cypress-assertions">Cypress Assertions</h3>
<p>These are Cypress commands that make assertions about the state of your application. They stop your test when they reach the time limit or the specified condition is fulfilled.</p>
<p>There are only two types of assertion commands: <code>.and()</code> and <code>.should()</code>. I'll discuss <code>.should()</code> here.</p>
<p>In Cypress, statements concerning the states of particular elements are made using the <code>.should()</code> command. It enables you to specify requirements that components must fulfill. In the event that the requirements are not satisfied, the test will fail.</p>
<h4 id="heading-fundamental-use-of-should">Fundamental Use of <code>.should()</code></h4>
<p>The basic syntax of <code>.should()</code> is as follows:</p>
<pre><code class="lang-javascript">cy.get(<span class="hljs-string">'selector'</span>).should(<span class="hljs-string">'condition'</span>, expectedValue);
</code></pre>
<ul>
<li><p>The DOM element(s) that you wish to make assertions against are chosen by <code>cy.get('selector')</code>.</p>
</li>
<li><p><code>.should('condition', expectedValue)</code> indicates what conditions and values the chosen element(s) must satisfy.</p>
</li>
</ul>
<p>You can also chain <code>.should()</code> assertions. Chained <code>.should()</code> statements are used to verify different conditions on the same element:</p>
<pre><code class="lang-javascript">cy.get(<span class="hljs-string">'input#username'</span>)
  .should(<span class="hljs-string">'be.visible'</span>)
  .should(<span class="hljs-string">'have.attr'</span>, <span class="hljs-string">'placeholder'</span>, <span class="hljs-string">'Enter your username'</span>)
</code></pre>
<p>In this example, we verify that the username input element is there and that the placeholder content is appropriate.</p>
<p><code>.should()</code> also allows you to use custom assertions by passing a callback function as the expected value:</p>
<pre><code class="lang-javascript">cy.get(<span class="hljs-string">'.my-element'</span>).should(<span class="hljs-function">(<span class="hljs-params">$element</span>) =&gt;</span> {
  expect($element).to.have.class(<span class="hljs-string">'active'</span>);
  expect($element).to.have.css(<span class="hljs-string">'color'</span>, <span class="hljs-string">'rgb(255, 0, 0)'</span>);
});
</code></pre>
<p>In this code, we're using custom assertions within <code>.should()</code> to check if the element has the class "active" and if its text color is red.</p>
<h4 id="heading-negating-assertions-with-should">Negating assertions with .should()</h4>
<p><code>.should('not.condition', expectedValue)</code> can be used to refute the following claims:</p>
<pre><code class="lang-javascript">cy.get(<span class="hljs-string">'#error-message'</span>).should(<span class="hljs-string">'not.exist'</span>);
</code></pre>
<p>This code verifies that there isn't an element with the ID "error-message".</p>
<h4 id="heading-combining-should-with-other-commands">Combining .should() with Other Commands</h4>
<p>To create testing scenarios with greater complexity, you can combine <code>.should()</code> with other Cypress commands. For instance, you can use it to assert the element's final state following a <code>.click()</code> or <code>.type()</code> command.</p>
<pre><code class="lang-javascript">cy.get(<span class="hljs-string">'button'</span>).click().should(<span class="hljs-string">'be.disabled'</span>);
cy.get(‘[data-testid=”search-input”]’).type(<span class="hljs-string">'Leonard'</span>).should(<span class="hljs-string">'have.value'</span>, <span class="hljs-string">'Leonard'</span>);
</code></pre>
<p>In these instances, we interact with the elements first (by clicking a button or entering text into an input box), and then we use the resultant states of the elements' states as determined by using <code>.should()</code>.</p>
<p>When constructing relevant assertions to confirm the behavior and state of items in your web application during end-to-end testing, Cypress's <code>.should()</code> command is a potent tool.</p>
<h3 id="heading-cypress-actions">Cypress Actions</h3>
<p>Cypress commands that interact with your program like a user would are called actions. They do not interact with the page until components or elements are actionable. There are numerous examples, but for now I'll use the <code>.click()</code> command.</p>
<p>To mimic a click on a DOM element in Cypress, use the <code>.click()</code> command. It's among the most typical and basic things you'll do in your end-to-end tests.</p>
<p>Let's look at an example of some code to demonstrate how to use <code>.click()</code>:</p>
<h4 id="heading-basic-click-usage">Basic <code>.Click()</code> Usage</h4>
<p>The following is the syntax of <code>.click()</code>:</p>
<pre><code class="lang-javascript">cy.get(<span class="hljs-string">'selector'</span>).click();
</code></pre>
<p>To choose the DOM element you want to click, use <code>cy.get('selector')</code>. <code>.click()</code> replicates a click event on the element that is chosen.</p>
<h4 id="heading-managing-clicks-during-user-interaction">Managing Clicks During User Interaction</h4>
<p>Sometimes, you may need to interact with things before clicking. For instance, you may want to complete a form field and press the submit button afterward. You can use <code>.type()</code> to communicate with input fields before continuing on to the submit button, <code>.click()</code>:</p>
<pre><code class="lang-javascript">cy.get(‘[data-testid=”username”]’).type(<span class="hljs-string">'okosaleo'</span>);
cy.get(‘[data-testid=”password”]’).type(<span class="hljs-string">'password'</span>);
cy.get(‘[data-testid=”Leo-button”]’).click();
</code></pre>
<p>First, in this case we employ <code>.type()</code> to input values in the password and username fields, and then click <code>.click()</code> to click the login button and submit the form.</p>
<h4 id="heading-managing-dynamic-elements">Managing Dynamic Elements</h4>
<p>You can utilize <code>.click()</code> while working with dynamic elements, or elements that emerge following an action. In order to make sure the element is there and prepared for interaction, you can use <code>.click()</code> in conjunction with other commands.</p>
<p>For instance, clicking a dynamic element. Assume you have a list of items and that you wish to click on a certain item that pops up following a certain amount of user interaction:</p>
<pre><code class="lang-javascript">cy.get(‘[data-testid=”Leo-button”]’).click();
cy.get(<span class="hljs-string">'.dynamic-item'</span>).should(<span class="hljs-string">'have.length.gt'</span>, <span class="hljs-number">5</span>);
cy.get(<span class="hljs-string">'.dynamic-item'</span>).eq(<span class="hljs-number">4</span>).click();
</code></pre>
<p>In this example, to load new things dynamically, we first click the <code>"Leo-button"</code> button. After making sure that at least six things are shown using <code>.should('have.length.gt', 5)</code>, we click the fifth item using <code>.eq(4)</code>.</p>
<h3 id="heading-other-commands">Other commands</h3>
<p>Cypress has many other commands which we haven't discussed here but that you can use to write other tests. You can check them out in the <a target="_blank" href="https://docs.cypress.io/api/table-of-contents">Cypress docs here</a>.</p>
<h2 id="heading-how-to-organize-and-run-your-cypress-tests">How to Organize and Run Your Cypress Tests</h2>
<p>Your application may accumulate a number of tests over time. Cypress offers several methods for setting them up and managing them effectively.</p>
<h3 id="heading-plugins">Plugins</h3>
<p>To assist with tasks such as creating code coverage reports and simulating APIs, Cypress offers a number of extensions and plugins.</p>
<p>Plugins are specially designed JavaScript modules that let you modify and add new features to the Cypress testing framework. With the use of plugins, you can increase Cypress's capabilities and customize it to suit your unique requirements.</p>
<p>Cypress plugins include:</p>
<ol>
<li><p>Integrations: Cypress may be integrated with other programs, services, and systems by the creation of plugins. Examples of these include deployment pipelines, version control systems, and platforms for continuous integration (CI).</p>
</li>
<li><p>Custom Commands: To encapsulate and reuse routine test procedures or user interactions with your application, you may define custom commands using plugins. This improves the organization and maintainability of your test code.</p>
</li>
</ol>
<p>There are many more plugin features that Cypress offers. Plugins are a flexible way to customize your testing framework to the specific needs of your project, increase the power of your testing, and organize and maintain your test code better.</p>
<h3 id="heading-describe-blocks">Describe Blocks</h3>
<p>The Mocha testing framework, which is integrated with Cypress to help you organize and structure your test suites, includes describe blocks. These describe blocks provide your tests a clear structure and help you group related test cases.</p>
<p>You can use describe blocks to categorize and explain the functionality and behavior of the program you are evaluating.</p>
<h4 id="heading-purpose-of-describe-blocks-in-cypress">Purpose of Describe Blocks in Cypress</h4>
<ul>
<li><p>Organize Test Cases: You can organize relevant test cases together by using the describe blocks. A description block can be made for a particular application feature, part, or functionality.</p>
</li>
<li><p>Enhance Test framework: They give your tests a hierarchical framework that makes the test suite easier to explore and comprehend. Developers and testers can find certain tests more quickly with the aid of this structure.</p>
</li>
<li><p>Clarity and Documentation: You can give titles for your tests that are both human-readable and descriptive by using describe blocks. This functions as a type of test documentation.</p>
</li>
</ul>
<p>A <code>describe</code> block is structured like this:</p>
<pre><code class="lang-javascript">describe(<span class="hljs-string">'Description of the Test Suite or Feature'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Your test cases (it blocks) go here</span>
});
</code></pre>
<ul>
<li><p><code>"Description of the Test Suite or Feature"</code>: This is a string that contains a description of the test suite or feature. It acts as the group of test cases title.</p>
</li>
<li><p><code>function () { /*... */ }</code>: This function holds the various test cases that are related to this <code>describe</code> block and are written within <code>it</code> blocks.</p>
</li>
</ul>
<h4 id="heading-how-to-use-describe-blocks-custom-commands">How to Use Describe Blocks Custom Commands</h4>
<p>Let's say you are evaluating a web application's login functionality. The following is how you could structure your tests using describe blocks:</p>
<pre><code class="lang-javascript">describe(<span class="hljs-string">'Login Feature'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// This is the outermost describe block for the Login Feature</span>

  it(<span class="hljs-string">'should display the login form'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Test case logic to check if the login form is displayed</span>
  });

  it(<span class="hljs-string">'should show an error message on invalid login'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Test case logic to check error message display</span>
  });

  it(<span class="hljs-string">'should log in successfully with valid credentials'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Test case logic to check successful login</span>
  });

  describe(<span class="hljs-string">'Password Reset'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Nested describe block for Password Reset functionality</span>

    it(<span class="hljs-string">'should allow users to request a password reset'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-comment">// Test case logic for password reset request</span>
    });

    it(<span class="hljs-string">'should reset the password with a valid reset token'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-comment">// Test case logic for password reset with a valid token</span>
    });
  });
});
</code></pre>
<p>In this instance:</p>
<ol>
<li><p>All of the test cases for the login feature are grouped together in the outermost describe block.</p>
</li>
<li><p>Tests pertaining to the password reset feature are grouped together in a describe block nestled within it.</p>
</li>
</ol>
<p>You can easily identify related tests thanks to this hierarchical structure, which also aids in clarifying the goals of each set of test cases.</p>
<p>Effective use of <code>describe</code> blocks in Cypress allows you to write well-structured and easily accessible test suites, which will facilitate test management and maintenance as your project expands.</p>
<h3 id="heading-custom-commands">Custom Commands</h3>
<p>To simplify repetitive tasks and improve the readability of your tests, you can create custom Cypress commands.</p>
<p>To encapsulate and reuse common test processes or interactions with the application being tested, you may develop and add custom commands—user-defined JavaScript functions—to your Cypress test suite. These can help augment the built-in Cypress commands and improve the readability, organization, and maintainability of your test code.</p>
<p>You need to define your custom command in one of your test files, usually the <code>commands.js</code> file. Often, you may find this file in the <code>cypress/support</code> directory.</p>
<p>On the other hand, you can arrange your customized commands in different files or folders according to the features of your program.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript">Cypress.Commands.add(<span class="hljs-string">'customCommandName'</span>, <span class="hljs-function">(<span class="hljs-params">arg0, arg1, ...</span>) =&gt;</span> {
  <span class="hljs-comment">// Define the custom command logic here</span>
});
</code></pre>
<ul>
<li><p><code>customCommandName</code>: This is the name that you'll use in your test scripts to identify your custom command.</p>
</li>
<li><p><code>(arg0, arg1,...)</code>: These are the parameters or arguments that you can give to the custom command in order to alter how the program behaves.</p>
</li>
<li><p><code>// Custom command logic }</code>: Here you provide the precise operations you wish to be carried out by your custom command.</p>
</li>
</ul>
<h4 id="heading-how-to-use-custom-commands">How to Use Custom Commands</h4>
<p>Once your custom command is defined, you can use it in your test scripts in the same way as any other Cypress command that is built-in.</p>
<p>Using the following syntax, you can invoke a custom command:</p>
<pre><code class="lang-javascript">cy.customCommandName(arg0, arg1, ...);
</code></pre>
<h4 id="heading-advantages-of-custom-commands">Advantages of Custom Commands</h4>
<p>Cypress custom commands have a number of advantages:</p>
<ol>
<li><p>Reusability: You can encapsulate intricate or commonly used interactions with your application using custom commands. This lessens redundancy in your test scripts and encourages the reuse of code.</p>
</li>
<li><p>Readability: Your test scripts become more accessible and understandable when typical tasks are abstracted into custom commands. Your test code will be more self-explanatory with custom commands.</p>
</li>
<li><p>Maintenance: Rather than having to look for and update each instance of an action in several test scripts, you just need to change the custom command once when you need to update a common action or interaction.</p>
</li>
<li><p>Consistency: Using custom commands guarantees that your test suite's common interactions are carried out in a consistent manner. This keeps the testing process consistent.</p>
</li>
</ol>
<p>This is a basic illustration of a custom command that allows a user to log in by filling out a login form with their username and password:</p>
<pre><code class="lang-javascript">Cypress.Commands.add(<span class="hljs-string">'login'</span>, <span class="hljs-function">(<span class="hljs-params">username, password</span>) =&gt;</span> {
  cy.get(‘[username-input”]’).type(username);
  cy.get(‘[data-testid=”password-input”]’).type(password);
  cy.get(‘[data-testid=”Leo-button”]’).click();
});
</code></pre>
<h3 id="heading-cypress-dashboard">Cypress Dashboard</h3>
<p>This tool lets you monitor films of text executors, organize test runs, and discuss outcomes with your team. You can find the Cypress dashboard in the test runner window.</p>
<p>To see the history of your test runs, click the "Runs" tab. The Runs tab will include a "View Dashboard" link at the top. When you click the "View Dashboard" link, your web browser will launch the Cypress Dashboard.</p>
<p>Cypress offers the dashboard as a web-based service. The goal of the Cypress Dashboard is to improve and streamline the web application testing and test management process. It provides a single platform to monitor, analyze, and manage your test runs using Cypress.</p>
<p>The Cypress Dashboard's main attributes and capabilities are as follows:</p>
<ol>
<li><p>Real-Time Test Execution: You can watch the test execution process in real time when you use the Cypress Dashboard service to execute Cypress tests. It offers a real-time view of your testing, including with videos and live browser screenshots. This tool is useful for tracking test progress and troubleshooting problems.</p>
</li>
<li><p>Collaboration and Sharing: The development and QA teams can work together thanks to the dashboard. Test results may be accessed and reviewed by developers, testers, and other stakeholders with ease when test runs are shared with team members.</p>
</li>
<li><p>Centralized Test Management: You can store and manage your Cypress test results centrally using the Cypress Dashboard. Test runs can be accessed and arranged from a single location.</p>
</li>
<li><p>The Cypress Dashboard facilitates the concurrent running of tests across many computers and web browsers. This can speed up the test execution process considerably and provide you the results you need more quickly.</p>
</li>
<li><p>Test Insights and Analytics: By tracking test results over time, you can learn more about your test runs. Comprehensive analytics, including execution times, pass/fail statuses, and more, are available in the Cypress Dashboard. You can use this data to find trends and patterns in your test results.</p>
</li>
<li><p>Test Automation and Scheduling: You can automate the testing process by scheduling tests to run at predetermined times or intervals. Running regression tests and maintaining ongoing test coverage can both benefit from this.</p>
</li>
</ol>
<p>These are some of the functions and attributes the Cypress dashboard offers.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/dashboard-analytics-overview.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Here's an example of what the cypress dashboard looks like</em></p>
<h2 id="heading-how-to-debug-your-code-with-cypress">How to Debug Your Code With Cypress</h2>
<p>It's simple to debug your tests with Cypress. To halt test execution and view an application's status in the browser, add <code>cy.debug()</code>. Let's look at an example of how to use <code>cy.debug</code> in Cypress:</p>
<pre><code class="lang-javascript">describe(<span class="hljs-string">'Cypress Debug Example'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'performs a login and checks the user profile'</span>, <span class="hljs-function">() =&gt;</span> {
    cy.visit(<span class="hljs-string">'/login'</span>);
    cy.get(<span class="hljs-string">'#username-input'</span>).type(<span class="hljs-string">'testuser'</span>);

    <span class="hljs-comment">// Pause the test execution to inspect the application state</span>
    cy.pause();

    cy.get(<span class="hljs-string">'#password-input'</span>).type(<span class="hljs-string">'password123'</span>);
    cy.get(<span class="hljs-string">'#login-button'</span>).click();

    <span class="hljs-comment">// Continue with assertions</span>
    cy.url().should(<span class="hljs-string">'include'</span>, <span class="hljs-string">'/profile'</span>);
    cy.get(<span class="hljs-string">'.user-info'</span>).should(<span class="hljs-string">'contain'</span>, <span class="hljs-string">'Welcome, testuser'</span>);
  });
});
</code></pre>
<p>In this example, the test will halt when it reaches the <code>cy.pause()</code> command, and the Cypress Test Runner will prompt you to view the DevTools console.</p>
<p>After that, you may interact with the program, examine the DOM, verify variables, and execute more Cypress commands interactively for debugging reasons via the console.</p>
<h4 id="heading-time-travel-debugging">Time Travel Debugging</h4>
<p>Cypress also has a powerful capability known as "Time Travel Debugging." This feature allows you to see the current state of your application at any time while it is being tested. This greatly simplifies the diagnosis process.</p>
<p>Using this feature, you can record and replay test execution stages to troubleshoot your Cypress tests. By giving you a visual depiction of the test execution process step-by-step, it assists you in identifying and resolving problems with your tests and application. Using Test Driven Development (TTD), you may see your application's state interactively at various stages of the test run.</p>
<p>This is how Cypress's Time Travel Debugging works:</p>
<p>You must first record a test run in order to use TTD. You may do this using the Cypress Dashboard service or by running your tests locally with the <code>--record</code> parameter.</p>
<p>This is an example of how to conduct testing while recording:</p>
<pre><code class="lang-bash">npx cypress run --record
</code></pre>
<p>The test is launched in the Electron browser by default.</p>
<p>Then you can use the Cypress Dashboard web interface once the test run is finished and the results are submitted to the Cypress Dashboard.</p>
<p>Next, find the test run you wish to debug in the Cypress Dashboard and click on it. This will direct you to the page with test specifics.</p>
<p>You may see a timeline representation of your application's state at each Cypress command execution on the test details page.</p>
<p>To see the state of the application at a certain moment in time, click on a snapshot on the timeline. You may browse console logs, work with the DOM, and even run Cypress commands in the context of that snapshot.</p>
<p>To examine the condition of the application at various test phases, you can either go to particular points in the timeline or walk through each command in the timeline one at a time.</p>
<p>This is an illustration of how to apply TTD in a Cypress test:</p>
<pre><code class="lang-javascript">describe(<span class="hljs-string">'Time Travel Debugging Example'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'performs a login and checks the user profile'</span>, <span class="hljs-function">() =&gt;</span> {
    cy.visit(<span class="hljs-string">'/login'</span>);
    cy.get(‘[username-input”]’).type(<span class="hljs-string">'testuser'</span>);
    cy.get(‘[password-input”]’).type(<span class="hljs-string">'password'</span>);
    cy.get(‘[login-input”]’).click();

    <span class="hljs-comment">// At this point, we may want to perform TTD to inspect the application's state</span>
    <span class="hljs-comment">// and ensure the user is returned to the profile page.</span>

    cy.url().should(<span class="hljs-string">'include'</span>, <span class="hljs-string">'/profile'</span>);
    cy.get(<span class="hljs-string">'.user-info'</span>).should(<span class="hljs-string">'contain'</span>, <span class="hljs-string">'Welcome, testuser'</span>);
  });
});
</code></pre>
<p>In this scenario, you may run into a problem that you wish to diagnose after entering your login information and hitting the login button.</p>
<p>To make sure the user is on the profile page and that their name is shown appropriately, you may use TTD to halt at the <code>cy.url()</code> assertion and verify the status of the application.</p>
<p>With TTD, you can examine the status of the application at different times to interactively debug and troubleshoot your Cypress tests, which will help you find and address problems more efficiently.</p>
<h2 id="heading-continuous-integration">Continuous Integration</h2>
<p>Cypress tests can be integrated into your continuous integration (CI) workflow using solutions like as Travis CI, GitHub actions, Jenkins, or CircleCI. Let's talk about continuous integration using Github actions:</p>
<h3 id="heading-cypress-continuous-integration-using-github-actions">Cypress Continuous Integration Using GitHub Actions</h3>
<p>You can automate the testing of your web apps with Cypress as part of your development workflow with Continuous Integration (CI) using GitHub Actions.</p>
<p>You can create workflows using GitHub Actions that automate a variety of processes, such as Cypress test runs, whenever changes are made to your source. Let's walk through how to get it set up.</p>
<p><strong>Prerequisites:</strong></p>
<ol>
<li><p>GitHub Repository: The Cypress tests and application code should be located in a GitHub repository.</p>
</li>
<li><p>Cypress Setup: Verify that Cypress is installed in your project and that your Cypress test configurations are accurate. Cypress Open may be used to set up and execute your tests locally.</p>
</li>
</ol>
<h4 id="heading-step-1-establish-a-workflow-configuration">Step 1: Establish a Workflow Configuration:</h4>
<p>Create a file in your GitHub repository called workflow configuration. The CI workflow is defined in this file, which is usually named <code>.github/workflows/cypress.yml</code>. It also provides instructions on when and how to execute Cypress tests.</p>
<p>This is an example of a simple configuration file:</p>
<pre><code class="lang-javascript">name: Cypress Tests

<span class="hljs-attr">on</span>:
  push:
    branches:
      - main # Align to your repository<span class="hljs-string">'s default branch

jobs:
  cypress:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    - name: Install dependencies
      run: npm install

    - name: Run Cypress tests
      run: npm run cypress:run</span>
</code></pre>
<p>Every time a push is made to the <code>main</code> branch, a process to execute Cypress tests is established by this configuration file. This may be altered to meet your needs.</p>
<h4 id="heading-step-2-describe-the-npm-scripts">Step 2: Describe the <code>npm</code> Scripts:</h4>
<p>Define <code>npm</code> scripts in your <code>package.json</code> file so that Cypress tests may be executed. For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"scripts"</span>: {
  <span class="hljs-string">"cypress:run"</span>: <span class="hljs-string">"cypress run"</span>,
  <span class="hljs-string">"cypress:open"</span>: <span class="hljs-string">"cypress open"</span>
}
</code></pre>
<p>While <code>cypress:open</code> is used to run tests interactively during development, <code>cypress:run</code> is used to execute Cypress tests in headless mode.</p>
<h4 id="heading-step-3-add-to-github-repo">Step 3: Add to GitHub Repo</h4>
<p>Add your application code and the GitHub Actions configuration file (cypress.yml) to your GitHub repository. Send the modifications to GitHub.</p>
<h4 id="heading-step-4-switch-on-github-actions">Step 4: Switch on GitHub Actions:</h4>
<p>If you haven't already, go to your GitHub repository, choose the "Actions" tab, and activate GitHub Actions for your repository.</p>
<h4 id="heading-step-5-manage-your-process">Step 5: Manage Your Process:</h4>
<p>GitHub Actions will launch the specified process, which includes your Cypress tests, automatically each time you post changes to your repository.</p>
<h4 id="heading-step-6-examine-the-results">Step 6: Examine the Results:</h4>
<p>The "Actions" page on your GitHub repository is where you can view the status and outcomes of your Cypress tests. Test results and logs will be displayed to you, allowing you to diagnose and look for any issues.</p>
<h3 id="heading-headless-option">Headless Option</h3>
<p>Cypress offers a headless option for continuous integration (CI) testing. Without the Cypress test runner, you can still run Cypress headlessly. By using the command <code>npx cypress run</code> this simply means there is no graphical user interface involved so the test runner isn't being deployed, here we mostly write scripts to use Cypress.</p>
<p>Web browsers that function without a graphical user interface, or headless browsers, are appropriate for automated testing in server contexts such as continuous integration/continuous delivery systems.</p>
<p>When you run Cypress tests in headless mode, no visible browser window is displayed during test execution. This is very helpful when testing without a user interface in an automated continuous integration and delivery pipeline.</p>
<p>To use this put the command <code>npx cypress run</code> in your terminal.</p>
<ol>
<li><p>Cypress will launch your test in an electron browser when you execute this command.</p>
</li>
<li><p>Upon completion, Cypress will automatically provide a video clip of the test run and screenshots in the event that a test fails, facilitating easy debugging.</p>
</li>
<li><p>The user can adjust screenshots and videos. The folder labeled "screenshots and videos" contains both screenshots and videos cypress produces.</p>
</li>
</ol>
<p>Another way of running tests is through adding scripts to your <code>package.json</code> file. You can add scripts which consist of the <code>key</code> and <code>value</code> pair that work as objects. with <code>key</code> being the name of the command and <code>value</code> being the command that's being run.</p>
<p>Let's run a test headlessly using a key value pair:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"script"</span>: {
    <span class="hljs-string">"cypress:run"</span>: <span class="hljs-string">"cypress run"</span>,
    <span class="hljs-string">"cypress:open"</span>: <span class="hljs-string">"cypress open"</span>
},
</code></pre>
<p>In this code <code>"cypress:run"</code> and <code>"cypress:open"</code> are the <code>keys</code> and <code>"cypress open"</code> and <code>"cypress open"</code> are the commands. To run the command we need the <code>npm run</code> followed by the key used example: <code>npm cypress:run</code>.</p>
<p>Hopefully you now understand how to run tests headlessly in Cypress.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Cypress is an effective tool you can use to test your web apps. You can use it to write end-to-end tests that make sure your React projects function as intended and identify any issues.</p>
<p>Cypress is a useful addition to your testing toolkit because of its interactive Test Runner, easy-to-use API, and robust debugging features. Now go ahead and use Cypress to test your React applications to make sure the user experience is seamless and error-free.</p>
<p>If you want to learn about Cypress in more detail, you can check out their documentation at <a target="_blank" href="https://www.freecodecamp.org/news/p/ee697448-b73d-43dd-85de-d31f1e1005c6/CYPRESS.IO">cypress.io</a>. Cheers to your testing!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
