<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Anoop Jadhav | Blogs]]></title><description><![CDATA[Anoop Jadhav, Blogs, Technical Blog, React js, React Native, Javascript, Typescript, Web development, UI design, User experience, Figma, Design]]></description><link>https://blog.anoopjadhav.in</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1727615338263/af0e9d38-78f7-412f-bfaa-f74a3be4d5b5.png</url><title>Anoop Jadhav | Blogs</title><link>https://blog.anoopjadhav.in</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 15 Nov 2026 00:14:13 GMT</lastBuildDate><atom:link href="https://blog.anoopjadhav.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Simple steps to Improve your website ranking on Google (SEO)]]></title><description><![CDATA[Learn simple, effective steps to improve your website ranking on Google.]]></description><link>https://blog.anoopjadhav.in/simple-steps-to-improve-your-website-ranking-on-google-seo</link><guid isPermaLink="true">https://blog.anoopjadhav.in/simple-steps-to-improve-your-website-ranking-on-google-seo</guid><category><![CDATA[SEO]]></category><category><![CDATA[Google]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[searchengineoptimization]]></category><category><![CDATA[search]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Wed, 09 Oct 2024 18:14:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730099570389/f42599d5-b509-43aa-a329-6695a057ef1a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently, I had the chance to work on SEO (Search Engine Optimization) for one of the projects. I learned a few things along the way. You can follow these steps:</p>
<p><mark>Google doesn’t accept any payment to make any website rank better, it all depends on the content</mark></p>
<h3 id="heading-pagespeed-insights-report">PageSpeed Insights Report</h3>
<p>You can check you app’s performance by using <a target="_blank" href="https://pagespeed.web.dev/">PageSpeed Insights</a>. This tool provides a detailed analysis of what can be improved in your web app regarding performance, accessibility, SEO &amp; best practices.</p>
<h3 id="heading-server-side-rendering">Server side rendering</h3>
<p>Server-side rendered (SSR) apps are generally better for SEO because they deliver fully-built pages directly from the server to the browser. This allows search engines to easily access and index the content, improving visibility and ranking. In contrast, client-side rendered (CSR) apps initially send a basic HTML page and rely on JavaScript to build the content after loading. This can create a delay, making it more challenging for search engines, especially older crawlers, to find and index the content effectively, potentially impacting SEO negatively.</p>
<h3 id="heading-title-description-and-keywords-on-every-page">Title, Description and Keywords on every page</h3>
<p>Add the following meta tags to the head of your webpage -</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Anoop Jadhav | Frontend Engineer<span class="hljs-tag">&lt;/<span class="hljs-name">title</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">"Frontend Engineer skilled in React and modern web technologies. View Anoop Jadhav's portfolio."</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"keywords"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"Anoop Jadhav, Frontend Engineer, React, Web Developer, Portfolio"</span> /&gt;</span>
</code></pre>
<h3 id="heading-add-sitemapxml-to-your-website">Add sitemap.xml to your website</h3>
<p>sitemap.xml contains all the links to all the internal pages/resources on your website. lean more about sitemap <a target="_blank" href="https://developers.google.com/search/docs/crawling-indexing/sitemaps/overview">here</a>.</p>
<p>This is how a sample sitemap.xml looks like -</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">urlset</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://www.sitemaps.org/schemas/sitemap/0.9"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">url</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">loc</span>&gt;</span>https://anoopjadhav.in/<span class="hljs-tag">&lt;/<span class="hljs-name">loc</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">lastmod</span>&gt;</span>2024-09-30<span class="hljs-tag">&lt;/<span class="hljs-name">lastmod</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">changefreq</span>&gt;</span>weekly<span class="hljs-tag">&lt;/<span class="hljs-name">changefreq</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">priority</span>&gt;</span>1.0<span class="hljs-tag">&lt;/<span class="hljs-name">priority</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">url</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- this is just a sample, ideally sitemaps can be huge, since it contains references to all the important resouces on your website--&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">urlset</span>&gt;</span>
</code></pre>
<p>Once you have your sitemap ready, upload this to <a target="_blank" href="https://search.google.com/search-console/about">google search console</a>. If you are new, signup on google search console, its completely free.</p>
<p>Also, keep this file in your public folder, so that it is publically accessible by crawlers.</p>
<p>for eg. - <a target="_blank" href="https://anoopjadhav.in/sitemap.xml">https://anoopjadhav.in/sitemap.xml</a></p>
<h3 id="heading-add-robottxt-to-your-website">Add robot.txt to your website</h3>
<p>This will help the crawler understand what part to the application is to be crawled and what part to avoid crawling (this will be useful when you don’t want certain parts of your application for eg api’s, private content to be visible to crawlers). learn more about crawlers <a target="_blank" href="https://developers.google.com/search/docs/crawling-indexing/robots/intro">here</a>.</p>
<h3 id="heading-symantic-html-tags">Symantic HTML Tags</h3>
<p>using proper <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Semantics">symantic tags</a> can also help google understand your content better.<br />few examples -</p>
<p>Using &lt;header&gt; tag for header of the page, h1 tag for title of the page etc. &lt;footer&gt; for footer content, &lt;nav&gt; for navigation items. These are just few of the examples but there are a lot of tags you can explore <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element#inline_text_semantics">here</a>.</p>
<h3 id="heading-interlinking-pages">Interlinking pages</h3>
<p>Interlinking page will help google find, index and undestand your pages better. It will also help the user navigate between pages easily.</p>
<h3 id="heading-avoid-gibberish-content">Avoid gibberish content</h3>
<p>Avoid gibberish content your website as it will affect the user experience and bounce rate which can degrade your ranking.</p>
<p>Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[Bring Your UI to Life: Creating Micro Interactions with Figma, Lottie & React]]></title><description><![CDATA[Micro interactions are common on most websites and mobile apps these days to enhance the user experience.]]></description><link>https://blog.anoopjadhav.in/bring-your-ui-to-life-creating-micro-interactions-with-figma-lottie-react</link><guid isPermaLink="true">https://blog.anoopjadhav.in/bring-your-ui-to-life-creating-micro-interactions-with-figma-lottie-react</guid><category><![CDATA[lottie-react]]></category><category><![CDATA[React]]></category><category><![CDATA[microinteraction]]></category><category><![CDATA[figma]]></category><category><![CDATA[Lottie]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Sat, 21 Sep 2024 08:02:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730099678650/77b5f655-f4ac-43c4-911e-971884ef9eb1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://uxdesign.cc/micro-interactions-why-when-and-how-to-use-them-to-boost-the-ux-17094b3baaa0">Micro interactions</a> are common on most websites and mobile apps these days to enhance the user experience.</p>
<p>I tried creating a simple micro interaction for my portfolio web app. While this could be done with CSS alone, but it is really complex. I found it easier to create complex animations using Figma and Lottie (though this does involve additional JSON files and the lottie-react library). The best part is that you can achieve this with a little knowledge of Figma.</p>
<p>I wanted to create a simple animation for a color picker since I couldn’t find a free version of the same online.</p>
<p>Follow these steps to add a simple micro interaction to your web app-</p>
<h2 id="heading-create-figma-design">Create Figma Design</h2>
<h3 id="heading-create-icon">Create Icon</h3>
<ol>
<li>Create a frame of your desired size. Since it's an icon, you can use standard sizes like 24, 32, etc. I chose 96.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726899688360/1aa173a0-4658-48e1-8148-77495db17eee.png" alt /></p>
<p>Do not add any fill to the frame so that your animation will have a transparent background.</p>
<p>I have created 3 elements on the frame -</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726898344831/fdf14856-59f4-42ad-bd26-c5a5ae7edf7a.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726898564048/ca7c452a-2a83-4802-8157-2e5a6b7a0562.png" alt /></p>
<ol start="2">
<li>Now we will create two states (2 frames) for the animation: <strong>open state</strong> and <strong>closed state</strong>. We already created the open state. Let's create a closed state by duplicating the current frame. (Select the current frame, press Alt, and drag). Now, adjust the elements based on the animation you want to create.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726898753071/2f6a266f-dabc-4ef1-906f-221a95e4c30d.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726898822313/4eb4f0ce-c7eb-49a5-9623-92cc02f9deb1.png" alt /></p>
<p>Make sure the frame still has all the 3 elements i.e. top, mid, last in our scenario. This will help with the animation using the smart animate feature in Figma.</p>
<h3 id="heading-create-prototype">Create Prototype</h3>
<p>Now lets add a <a target="_blank" href="https://help.figma.com/hc/en-us/articles/360040314193-Guide-to-prototyping-in-Figma">prototype</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726899004910/1c6e6504-d8e1-4b99-98f9-d44b2d835030.png" alt /></p>
<p>We want our animation to go from the <strong>closed state</strong> to the <strong>open state</strong>. Our starting point will be the <strong>closed state</strong> frame.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726899073113/f16674c9-ec1a-4ecd-8d51-4942a37adf56.png" alt /></p>
<p>Now add an interaction between the frames.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726899305256/74bcdeea-a72c-4246-bc5a-7b2844f6449b.png" alt /></p>
<p>Thats it.</p>
<h2 id="heading-export-prototype-to-lottie">Export prototype to Lottie</h2>
<ol>
<li>Add Lottie plugin to figma</li>
</ol>
<p>Go to Menu &gt; Plugins &gt; Manage Plugins &gt; search for Lottie and add the plugin. You will need to create a Lottie account as well.</p>
<p>Should open a small window like this -</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726900124108/ac26c84a-5353-4b2d-8664-c7e7993399ac.png" alt /></p>
<ol start="2">
<li>Select your starting frame and click on save to workspace.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726900494618/23af7373-0240-41cb-87e0-97aa030b160f.gif" alt /></p>
<p>This will export your prototype to lottie.</p>
<h2 id="heading-download-lottie-json-file">Download Lottie JSON file</h2>
<p>Go to <a target="_blank" href="https://app.lottiefiles.com/">app.lottiefiles.com</a> and select the uploaded animation file to open the editor. Then download the Lottie JSON file.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726900912737/19ea925f-60bb-4ec1-b307-b26bc27b97ac.png" alt /></p>
<h2 id="heading-add-lottie-animation-to-react-component">Add lottie animation to react component</h2>
<ol>
<li><p>Add the Lottie JSON file to your repository.</p>
</li>
<li><p>Add the <a target="_blank" href="https://www.npmjs.com/package/lottie-react"><code>lottie-react</code></a> package to your repository.</p>
</li>
<li><p>Create a React component to display the Lottie animation.</p>
</li>
</ol>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { useLottie } <span class="hljs-keyword">from</span> <span class="hljs-string">'lottie-react'</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> lottieData <span class="hljs-keyword">from</span> <span class="hljs-string">'./ColorSwatchIcon.json'</span>

<span class="hljs-keyword">const</span> ColorPicker = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { View, setSpeed, play, setDirection } = useLottie(
        {
            animationData: lottieData,
            loop: <span class="hljs-literal">false</span>,
            autoplay: <span class="hljs-literal">false</span>,
        }
    )

    setSpeed(<span class="hljs-number">1</span>)

    <span class="hljs-keyword">return</span> (
        &lt;div
            className=<span class="hljs-string">"color-picker"</span>
            onMouseEnter={<span class="hljs-function">() =&gt;</span> {
                setDirection(<span class="hljs-number">1</span>)
                play()
            }}
            onMouseLeave={<span class="hljs-function">() =&gt;</span> {
                setDirection(<span class="hljs-number">-1</span>)
                play()
            }}
        &gt;
           {View}
        &lt;/div&gt;
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ColorPicker
</code></pre>
<p>And that's it, you have created a simple micro-interaction which plays the animation on hover.</p>
<p><strong>Hope this helps. Thanks for reading.</strong></p>
]]></content:encoded></item><item><title><![CDATA[You don't need a store with React Hook Forms]]></title><description><![CDATA[Discover how React Hook Form simplifies form management in React apps. Learn how react hook form eliminates boiler plate code.]]></description><link>https://blog.anoopjadhav.in/we-dont-need-a-local-state-with-react-hook-forms</link><guid isPermaLink="true">https://blog.anoopjadhav.in/we-dont-need-a-local-state-with-react-hook-forms</guid><category><![CDATA[React]]></category><category><![CDATA[react-hook-form]]></category><category><![CDATA[form validation]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Fri, 31 May 2024 16:55:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730099754713/0a75d262-a006-4dbb-9d15-45aea5515d4a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h4 id="heading-story-behind-the-blog">Story Behind the Blog</h4>
<p>Until recently, we managed all our form data using MobX. However, after introducing React Hook Form, form validation became much simpler. We realized that there was no need to save the form data in multiple places since React Hook Form manages its own state. This eliminated a lot of code for us.</p>
<h4 id="heading-what-is-react-hook-form">What is React Hook Form?</h4>
<p><a target="_blank" href="https://react-hook-form.com/">React Hook Form</a> is a lightweight library that uses React hooks to handle form state and validation. It fits right into the existing React component structure, making it easy to build and manage forms without a lot of extra code.</p>
<h4 id="heading-why-you-dont-need-a-separate-state">Why You Don’t Need a Separate State</h4>
<p>Managing form state usually means keeping track of local state with the useState hook, Context API, or a state management library like <a target="_blank" href="https://redux.js.org/">Redux</a> or <a target="_blank" href="https://mobx.js.org/README.html">Mobx</a>. However, React Hook Form takes care of this for you by providing its own context api.</p>
<h4 id="heading-getting-started-with-react-hook-form">Getting Started with React Hook Form</h4>
<pre><code class="lang-bash">npm install react-hook-form --save
</code></pre>
<p>Now, let's create a basic form component using React Hook Form:</p>
<pre><code class="lang-typescript"><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> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;

<span class="hljs-keyword">const</span> SimpleForm = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { register, handleSubmit, watch, formState: { errors } } = useForm();
  <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
    <span class="hljs-comment">// make api call to save the form</span>
    alert(<span class="hljs-built_in">JSON</span>.stringify(data));
  }

  <span class="hljs-built_in">console</span>.log(watch(<span class="hljs-string">"example"</span>)); <span class="hljs-comment">// watch input value by passing the name of it</span>

  <span class="hljs-keyword">return</span> (
    &lt;form onSubmit={handleSubmit(onSubmit)} noValidate&gt;
      &lt;input {...register(<span class="hljs-string">"example"</span>)} /&gt;
      {errors.example &amp;&amp; &lt;span&gt;This field is required&lt;/span&gt;}

      &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> SimpleForm;
</code></pre>
<p>In this example, the <code>useForm</code> hook provides several methods and properties to manage the form:</p>
<ul>
<li><p><code>register</code>: A function to register input fields.</p>
</li>
<li><p><code>handleSubmit</code>: A function to handle form submission.</p>
</li>
<li><p><code>watch</code>: A function to watch the value of a specific input field.</p>
</li>
<li><p><code>formState</code>: An object containing the form's state, including validation errors.</p>
</li>
</ul>
<h4 id="heading-handling-validation">Handling Validation</h4>
<p>React Hook Form makes form validation simple and declarative. You can specify validation rules directly within the <code>register</code> function. Here’s an example:</p>
<pre><code class="lang-typescript"><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> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;

<span class="hljs-keyword">const</span> ValidationForm = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { register, handleSubmit, formState: { errors } } = useForm();

  <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
    <span class="hljs-comment">// make api call to save the form</span>
    alert(<span class="hljs-built_in">JSON</span>.stringify(data));
  }

  <span class="hljs-keyword">return</span> (
    &lt;form onSubmit={handleSubmit(onSubmit)} noValidate&gt;
      &lt;input {...register(<span class="hljs-string">"username"</span>, { required: <span class="hljs-literal">true</span> })} /&gt;
      {errors.username &amp;&amp; &lt;span&gt;This field is required&lt;/span&gt;}

      &lt;input {...register(<span class="hljs-string">"email"</span>, { 
        required: <span class="hljs-string">"Email is required"</span>, 
        pattern: {
          value: <span class="hljs-regexp">/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/</span>,
          message: <span class="hljs-string">"Invalid email address"</span>
        }
      })} /&gt;
      {errors.email &amp;&amp; &lt;span&gt;{errors.email.message}&lt;/span&gt;}
       &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ValidationForm;
</code></pre>
<p>In this example, we've added validation rules for the <code>username</code> and <code>email</code> fields. If the validation rules are not met, error messages will be displayed. We can simplify adding validation even more by using popular libraries like <a target="_blank" href="https://zod.dev/">Zod</a> or <a target="_blank" href="https://www.npmjs.com/package/yup">Yup</a>.</p>
<p>here is how we can simplify this further by using zod -</p>
<pre><code class="lang-typescript"><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> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;
<span class="hljs-keyword">import</span> { zodResolver } <span class="hljs-keyword">from</span> <span class="hljs-string">'@hookform/resolvers/zod'</span>;
<span class="hljs-keyword">import</span> { z } <span class="hljs-keyword">from</span> <span class="hljs-string">'zod'</span>;

<span class="hljs-comment">// Define your schema with zod</span>
<span class="hljs-keyword">const</span> schema = z.object({
  username: z.string().nonempty({ message: <span class="hljs-string">"This field is required"</span> }),
  email: z.string().nonempty({ message: <span class="hljs-string">"Email is required"</span> }).email({ message: <span class="hljs-string">"Invalid email address"</span> }),
});

<span class="hljs-keyword">const</span> ValidationFormWithZod = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { register, handleSubmit, formState: { errors } } = useForm({
    resolver: zodResolver(schema),
  });

  <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
    <span class="hljs-comment">// make api call to save the form</span>
    alert(<span class="hljs-built_in">JSON</span>.stringify(data));
  }

  <span class="hljs-keyword">return</span> (
    &lt;form onSubmit={handleSubmit(onSubmit)} noValidate&gt;
      &lt;div&gt;
        &lt;input {...register(<span class="hljs-string">"username"</span>)} /&gt;
        {errors.username &amp;&amp; &lt;span&gt;{errors.username.message}&lt;/span&gt;}
      &lt;/div&gt;

      &lt;div&gt;
        &lt;input {...register(<span class="hljs-string">"email"</span>)} /&gt;
        {errors.email &amp;&amp; &lt;span&gt;{errors.email.message}&lt;/span&gt;}
      &lt;/div&gt;

      &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ValidationFormWithZod;
</code></pre>
<h4 id="heading-eliminating-the-need-for-separate-state">Eliminating the Need for Separate State</h4>
<p>By leveraging the <code>useForm</code> hook, React Hook Form manages the form state internally. This means you don't need to use <code>useState</code> to manage input values or validation errors. React Hook Form takes care of updating the form state as users interact with the form, making your code cleaner and more maintainable.</p>
<p>Consider a traditional approach with <code>useState</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> TraditionalForm = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [formData, setFormData] = useState({ username: <span class="hljs-string">''</span>, email: <span class="hljs-string">''</span> });
  <span class="hljs-keyword">const</span> [errors, setErrors] = useState({});

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();
    <span class="hljs-keyword">const</span> newErrors = {};
    <span class="hljs-keyword">if</span> (!formData.username) newErrors.username = <span class="hljs-string">"Username is required"</span>;
    <span class="hljs-keyword">if</span> (!formData.email) {
      newErrors.email = <span class="hljs-string">"Email is required"</span>;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!<span class="hljs-regexp">/\S+@\S+\.\S+/</span>.test(formData.email)) {
      newErrors.email = <span class="hljs-string">"Email is invalid"</span>;
    }
    setErrors(newErrors);
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.keys(newErrors).length === <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">console</span>.log(formData);
        <span class="hljs-comment">// make api call to save the form</span>
        alert(<span class="hljs-built_in">JSON</span>.stringify(data));
    }
  };

  <span class="hljs-keyword">return</span> (
    &lt;form onSubmit={handleSubmit} noValidate&gt;
      &lt;input 
        name=<span class="hljs-string">"username"</span>
        value={formData.username}
        onChange={handleChange}
      /&gt;
      {errors.username &amp;&amp; &lt;span&gt;{errors.username}&lt;/span&gt;}

      &lt;input 
        name=<span class="hljs-string">"email"</span>
        value={formData.email}
        onChange={handleChange}
      /&gt;
      {errors.email &amp;&amp; &lt;span&gt;{errors.email}&lt;/span&gt;}

       &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> TraditionalForm;
</code></pre>
<p>In this traditional approach, you manage form state and validation manually using <code>useState</code>. This can quickly become cumbersome as the form complexity grows. React Hook Form simplifies this by handling the form state internally, reducing the amount of boilerplate code you need to write.</p>
<h4 id="heading-thanks-for-reading">Thanks for reading !</h4>
]]></content:encoded></item><item><title><![CDATA[Migrating to Vite,Vitest?]]></title><description><![CDATA[Follow the steps to make a switch to vite.]]></description><link>https://blog.anoopjadhav.in/migrating-to-vitevitest</link><guid isPermaLink="true">https://blog.anoopjadhav.in/migrating-to-vitevitest</guid><category><![CDATA[vite]]></category><category><![CDATA[vitest]]></category><category><![CDATA[refactoring]]></category><category><![CDATA[React]]></category><category><![CDATA[Jest]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Wed, 25 Jan 2023 15:44:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730099798046/33fdc8b5-676b-44fe-b4eb-3e34ce8b4a31.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We recently migrated our project from Parcel to Vite and the reasons for doing so are in <a target="_blank" href="https://creativedevs.hashnode.dev/why-i-switched-from-parcel-to-vite">this article</a>. Even though migrating from Parcel to Vite may not be as difficult as migrating from Webpack to Vite, this article can help you identify the essential elements that need to be set up on the Vite side.</p>
<h2 id="heading-install-vite-packages">Install Vite packages</h2>
<p>The first step is to ensure that all the necessary Vite-specific dependencies are correctly installed.</p>
<p><code>npm i -D vite @vitejs/plugin-react vite-plugin-checker</code></p>
<p><strong>@vitejs/plugin-react</strong> enables React support in a Vite project.</p>
<p><strong>vite-plugin-checker</strong> helps in identifying typescript errors while developing.</p>
<h2 id="heading-add-vite-config-file">Add Vite Config file</h2>
<p>Add a config file in the root directory. checkout the following config -</p>
<p><em>vite.config.ts</em></p>
<pre><code class="lang-typescript"><span class="hljs-comment">/// &lt;reference types="vite/client" /&gt; </span>
<span class="hljs-comment">// Add the above line if you are using typescript. </span>

<span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>;
<span class="hljs-keyword">import</span> checker <span class="hljs-keyword">from</span> <span class="hljs-string">'vite-plugin-checker'</span>;
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">'@vitejs/plugin-react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; {
    <span class="hljs-keyword">return</span> defineConfig({
        plugins: [
            react(),
            checker({
                typescript: <span class="hljs-literal">true</span>,
            }),
        ],
        build: {
            outDir: <span class="hljs-string">'../dist'</span>,
        },
        server: {
            port: <span class="hljs-number">8080</span>,
        },
        root: <span class="hljs-string">'./src'</span>
    });
};
</code></pre>
<h2 id="heading-add-scripts-in-packagejson">Add scripts in package.json</h2>
<p>Include the start and build scripts in the <em>package.json</em> file.</p>
<p><em>package.json</em></p>
<pre><code class="lang-json">
<span class="hljs-string">"scripts"</span>: {
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"vite build --base=/base-path-if-any/ --config vite.config.ts"</span>,
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"vite --config vite.config.ts"</span>
}
</code></pre>
<p>If you are deploying your project under a nested public path ( otherwise ignore this step), simply specify the <a target="_blank" href="https://vitejs.dev/config/shared-options.html#base">base config option</a> and all asset paths will be rewritten accordingly. This option can also be specified as a command line flag, e.g. <code>vite build --base=/my/public/path/</code>.</p>
<h2 id="heading-update-environment-variables">Update Environment variables</h2>
<p>Vite exposes all the environment variables on <strong>import.meta.env</strong></p>
<p>so you can access your environment variables like <strong>import.meta.env.VITE_MY_ENV_VARIABLE</strong></p>
<p>It is important to prefix all the environment variables with <strong>VITE_</strong> since it prevents the accidental leaking of environment variable data to the client.</p>
<p><a target="_blank" href="https://vitejs.dev/guide/env-and-mode.html">read more</a></p>
<h2 id="heading-add-vitest">Add Vitest</h2>
<h3 id="heading-add-vite-packages">Add vite packages</h3>
<p><code>npm i -D vitest @vitest/coverage-c8 @vitest/ui</code></p>
<h3 id="heading-add-test-scripts">Add test scripts</h3>
<p>Update the package.json with the following test-specific scripts -</p>
<p><em>package.json</em></p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span> : {
       <span class="hljs-comment">// ... other build scripts</span>
      <span class="hljs-attr">"test"</span>: <span class="hljs-string">"vitest"</span>,
      <span class="hljs-attr">"test:ui"</span>: <span class="hljs-string">"vitest --ui"</span>,
      <span class="hljs-attr">"test:coverage"</span>: <span class="hljs-string">"vitest --coverage"</span>,
      <span class="hljs-attr">"test:watch"</span>: <span class="hljs-string">"vitest --watch"</span>,
}
</code></pre>
<h3 id="heading-update-vite-config">Update vite config</h3>
<p>Update the test setup in vite config.</p>
<pre><code class="lang-typescript">        test: {
            globals: <span class="hljs-literal">true</span>,
            environment: <span class="hljs-string">'jsdom'</span>,
            setupFiles: [<span class="hljs-string">'../setupTests.ts'</span>]
        }
</code></pre>
<p>update setupFiles if there are any test setup files which you want to run before running the actual unit tests.</p>
<p>here we are using jsdom as our test environment. so we will have to install jsdom.</p>
<p><code>npm i -D jsdom</code></p>
<p>Now the config file should look like -</p>
<p><em>vite.config.ts</em></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// include this to add types support</span>
<span class="hljs-comment">/// &lt;reference types="vitest" /&gt;</span>
<span class="hljs-comment">/// &lt;reference types="vite/client" /&gt;</span>

<span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>;
<span class="hljs-keyword">import</span> checker <span class="hljs-keyword">from</span> <span class="hljs-string">'vite-plugin-checker'</span>;
<span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">'@vitejs/plugin-react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; {
    <span class="hljs-keyword">return</span> defineConfig({
        plugins: [
            react(),
            checker({
                typescript: <span class="hljs-literal">true</span>,
            }),
        ],
        build: {
            outDir: <span class="hljs-string">'../dist'</span>,
        },
        server: {
            port: <span class="hljs-number">8080</span>,
        },
        root: <span class="hljs-string">'./src'</span>,
        test: {
            globals: <span class="hljs-literal">true</span>,
            environment: <span class="hljs-string">'jsdom'</span>,
            setupFiles: [<span class="hljs-string">'../setupTests.ts'</span>],
        }
    });
};
</code></pre>
<p>migration from jest to vitest is pretty easy but in our scenario, the number of tests was pretty high and the performance improvement which vitest was claiming was not much evident. because of this, we thought of sticking to jest for some more time.</p>
<p>checkout the <a target="_blank" href="https://vitest.dev/guide/migration.html">migration guide</a> if you want to move from jest to vitest.</p>
<h2 id="heading-how-to-make-it-work-with-jest">How to make it work with Jest?</h2>
<p>The only challenge when using Jest with Vite is the way we import environment variables, i.e. <code>import.meta.env</code>. To make it work with Jest, we need to revert to the <code>process.env</code> implementation. Remember, we changed this in the "<strong>Update Environment</strong>" section above.</p>
<p>We can use the <code>define</code> attribute in Vite to import environment variables more efficiently. Instead of using <code>process.env</code>, we can add the environment variables directly to the <code>define</code> attribute when creating the Vite instance. For example:</p>
<pre><code class="lang-typescript">defineConfig({
  define: {
    MY_ENVIRONMENT_VARIABLE: process.env.MY_ENVIRONMENT_VARIABLE
  }
});
</code></pre>
<p>Now the config file would look like this -</p>
<p><em>vite.config.ts</em></p>
<pre><code class="lang-typescript"><span class="hljs-comment">/// &lt;reference types="vitest" /&gt;</span>
<span class="hljs-comment">/// &lt;reference types="vite/client" /&gt;</span>

<span class="hljs-keyword">import</span> { defineConfig, loadEnv } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>;
<span class="hljs-keyword">import</span> checker <span class="hljs-keyword">from</span> <span class="hljs-string">'vite-plugin-checker'</span>;
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">'@vitejs/plugin-react'</span>;

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ({ mode }: ViteConfigProps) =&gt; {
    <span class="hljs-keyword">const</span> env = loadEnv(mode, process.cwd());

    <span class="hljs-comment">// expose .env as process.env instead of import.meta since jest does not not support import meta yet</span>
    <span class="hljs-keyword">const</span> processEnvValues = {
        <span class="hljs-string">'process.env'</span>: <span class="hljs-built_in">Object</span>.entries(env).reduce(<span class="hljs-function">(<span class="hljs-params">prev, [key, val]</span>)             =&gt;</span> {
            <span class="hljs-keyword">return</span> {
                ...prev,
                [key]: val,
            };
        }, {}),
    };

    <span class="hljs-keyword">return</span> defineConfig({
        plugins: [
            react(),
            checker({
                typescript: <span class="hljs-literal">true</span>,
            }),
        ],
        build: {
            outDir: <span class="hljs-string">'../dist'</span>,
        },
        server: {
            port: <span class="hljs-number">8080</span>,
        },
        root: <span class="hljs-string">'./src'</span>,
        define: processEnvValues,
    });
};
</code></pre>
<p>This will get you started with the project migration.</p>
<p>I will be updating this article with the following topics very soon -</p>
<ol>
<li><p><strong>Adding Aliases</strong></p>
</li>
<li><p><strong>Code Splitting</strong></p>
</li>
</ol>
<p>Thanks for reading !</p>
]]></content:encoded></item><item><title><![CDATA[Why I switched from Parcel to Vite ?]]></title><description><![CDATA[Vite - Speeds up the local build time, HMR(hot module replacement) is incredibly fast. Loads the changes in no time.]]></description><link>https://blog.anoopjadhav.in/why-i-switched-from-parcel-to-vite</link><guid isPermaLink="true">https://blog.anoopjadhav.in/why-i-switched-from-parcel-to-vite</guid><category><![CDATA[Bundler]]></category><category><![CDATA[parcel]]></category><category><![CDATA[vite]]></category><category><![CDATA[React]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Fri, 02 Dec 2022 14:46:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730099888012/bc3796b2-a535-49f3-b3cb-ef8f76680665.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>We have recently switched from parcel to Vite in one of my frontend projects(tech stack - Yarn Monorepos, React, Typescript, Styled Components, Jest, RTL). we were facing the problem of HMR since we were using mono repos, so decided to give a shot at vite and the results were incredible. <strong>Vite is fast!</strong></p>
<h2 id="heading-reasons-for-switch">Reasons for switch</h2>
<ol>
<li><p>Parcel is a zero-config tool. It simplifies the project setup at the <strong>cost of cache issues, poor HMR and slower build times</strong>. This problem will be more evident in bigger projects. I still recommend Parcel for people who are starting out new or don't want to worry about the project setup.</p>
</li>
<li><p>Vite - <strong>Speeds up</strong> the <strong>local build</strong> time.</p>
</li>
<li><p>Vite - <strong>HMR(hot module replacement) is incredibly fast</strong>. Loads the changes in no time. Vite internally uses Rollup as a bundler but they are planning to use esbuild in future which might make it even faster for production builds. <a target="_blank" href="https://vitejs.dev/guide/why.html">Click to know more.</a></p>
</li>
</ol>
<h2 id="heading-some-positives-and-negatives-of-parcel-and-vite">Some positives and negatives of parcel and Vite</h2>
<h3 id="heading-parcel"><strong>Parcel</strong></h3>
<p><em>Positives</em></p>
<ol>
<li><p>Seriously Zero Config. This is the tool you should go for if you are a newbie or don't want to scratch your head around project setup.</p>
</li>
<li><p>Great tooling support especially lint and typescript support.</p>
</li>
<li><p>Prod builds are equally fast as Vite.</p>
</li>
</ol>
<p><em>Negatives</em></p>
<ol>
<li><p>Cache issues especially when working with mono-repository.</p>
</li>
<li><p>HMR delay. Take a lot of time to reflect the changes on the browser which can be because of the cache it maintains. The browser gets into the loading state and never recovers from it, the only solution is to close the tab or restart the parcel build script.</p>
</li>
</ol>
<h3 id="heading-vite"><strong>Vite</strong></h3>
<p><em>Positives</em></p>
<ol>
<li><p>Incredibly fast build times, especially local builds but comparatively prod build might take more time.</p>
</li>
<li><p>HMR works like a charm. The browser reflects the changes in no time. Hardly there are times when I have to go and refresh the page.</p>
</li>
</ol>
<p><em>Negatives</em></p>
<ol>
<li><p>Tooling support for lint and typescript is not that great as of now. I am using <code>vite-plugin-checker</code> for highlighting typescript issues.</p>
</li>
<li><p>Little Config overhead. It needs you to go through the docs to set up the project but I feel it's minimal. Far better than webpack config.</p>
</li>
<li><p>Changes are required for environment variables for eg. env variables are now exposed on <code>import.meta.env</code> and they have to be appended with <code>VITE_</code> for it to be accessible in the project. <a target="_blank" href="https://vitejs.dev/guide/env-and-mode.html">Click here to know more</a>. Jest test setup might start throwing errors because now the environment variables are not directly accessible on <code>process</code> object. But there is still a way to fix that by using the <code>define</code> attribute in <code>vite.config.js</code> . <a target="_blank" href="https://vitejs.dev/guide/build.html">Click here to know more</a>.</p>
</li>
</ol>
<p>I will cover the setup part for <strong>React, Typescript, Jest + Vite</strong> in upcoming blog.</p>
<p>Feel free to share your thoughts in the comments.</p>
<p><mark>Thanks for reading!</mark></p>
]]></content:encoded></item><item><title><![CDATA[Why snapshot testing is not enough?]]></title><description><![CDATA[While snapshot testing is a good way to capture the state of the DOM, it is not the best way to test your functionality.]]></description><link>https://blog.anoopjadhav.in/why-snapshot-testing-is-not-enough</link><guid isPermaLink="true">https://blog.anoopjadhav.in/why-snapshot-testing-is-not-enough</guid><category><![CDATA[unit testing]]></category><category><![CDATA[snapshot testing]]></category><category><![CDATA[react testing library]]></category><category><![CDATA[Jest]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Wed, 28 Sep 2022 07:14:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730099980635/417c92fa-a6ce-4f26-8437-41088a8be832.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>I came across this question in one of the unit testing discussions so thought of sharing it with everyone else. I will not be covering what is snapshot testing in this article. Please check this <a target="_blank" href="https://jestjs.io/docs/snapshot-testing#does-snapshot-testing-replace-unit-testing">link</a> for more info about snapshot testing.</p>
<p>Well, snapshot testing is a <strong>good way to capture the state of the DOM (Document Object Model)</strong>. It will help you identify if your code has made any DOM-level changes.</p>
<p>Let's take an example by creating a <strong>Todo App</strong> -</p>
<p><code>App.tsx</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./style.css'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [todos, setTodos] = useState&lt;<span class="hljs-built_in">Array</span>&lt;string&gt;&gt;([]);
  <span class="hljs-keyword">const</span> [todoInput, setTodoInputValue] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> addTodoItem = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (todoInput) {
      setTodos([...todos, todoInput]);
      setTodoInputValue(<span class="hljs-string">''</span>);
    }
  };

  <span class="hljs-keyword">const</span> clearTodoList = <span class="hljs-function">() =&gt;</span> {
    setTodos([]);
  };

  <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">h2</span>&gt;</span>Todo List<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"todo-items"</span>&gt;</span>
        {todos.map((todo) =&gt; (
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{todo}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        ))}
      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span>
        <span class="hljs-attr">data-testid</span>=<span class="hljs-string">"input"</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{todoInput}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setTodoInputValue(e.target.value)}
      /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"buttons-wrapper"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"reset"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{clearTodoList}</span>&gt;</span>
          Clear
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{addTodoItem}</span>&gt;</span>Add<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span 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><a target="_blank" href="https://stackblitz.com/edit/react-ts-vqe4dr?file=package.json">checkout the code in action</a></p>
<h3 id="heading-adding-snapshot-test">Adding Snapshot Test</h3>
<p>Let's add some unit tests to test for this component</p>
<p><code>App.test.tsx</code></p>
<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> { render } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>;

describe(<span class="hljs-string">'&lt;App/&gt;'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'should match the snapshot'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> container = render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);
    expect(container.container).toMatchSnapshot();
  });
});
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/react-ts-vqe4dr?file=package.json">checkout the code in action</a></p>
<p>This will generate the following snapshot in __<strong>snapshots__</strong> directory -</p>
<pre><code class="lang-xml">// Jest Snapshot v1

exports[`<span class="hljs-tag">&lt;<span class="hljs-name">App</span>/&gt;</span> should match the snapshot 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>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>
      Todo List
    <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"todo-items"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"buttons-wrapper"</span>
    &gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"reset"</span>
      &gt;</span>
        Clear
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>
        Add
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span 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><a target="_blank" href="https://stackblitz.com/edit/react-ts-vqe4dr?file=package.json">checkout the code in action</a></p>
<p>the above snapshot contains all the DOM elements along with the labels and element attributes. So this is a good way to test the structure or hierarchy of the DOM. but, <strong>it will not capture the events and any other methods in your component.</strong></p>
<h3 id="heading-how-do-we-capture-methods-and-events-in-the-snapshot-tests">how do we capture methods and events in the snapshot tests?</h3>
<p>Although we cannot capture the code of the methods in the snapshot, we can capture the DOM changes which were caused by the execution of methods or events.</p>
<p>let's add one more snapshot to test the add method -</p>
<p><code>App.test.tsx</code></p>
<pre><code class="lang-javascript">  it(<span class="hljs-string">'should match the snapshot when a todo item is added'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> renderResult = render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);
    <span class="hljs-keyword">const</span> inputElement = renderResult.getByTestId(<span class="hljs-string">'input'</span>);
    <span class="hljs-keyword">const</span> addButton = renderResult.getByText(<span class="hljs-string">'Add'</span>);
    fireEvent.change(inputElement, { <span class="hljs-attr">target</span>: { <span class="hljs-attr">value</span> : <span class="hljs-string">"Todo Item 1"</span>}});
    fireEvent.click(addButton);
    expect(renderResult.container).toMatchSnapshot();
  });
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/react-ts-vqe4dr?file=package.json">checkout the code in action</a></p>
<p>This will generate the following snapshot -</p>
<pre><code class="lang-xml">exports[`<span class="hljs-tag">&lt;<span class="hljs-name">App</span>/&gt;</span> should match the snapshot when a todo item is added 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>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>
      Todo List
    <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"todo-items"</span>
    &gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>
        Todo Item 1
      <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span>
      <span class="hljs-attr">data-testid</span>=<span class="hljs-string">"input"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"buttons-wrapper"</span>
    &gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"reset"</span>
      &gt;</span>
        Clear
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>
        Add
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span 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>Now you can see the new <strong>Todo Item 1</strong> added via a unit test in the snapshot. This tested <strong>addTodoItem</strong> method.</p>
<p>This is how you can test <strong>some of the internal workings</strong> of the component but at the <strong>cost of additional snapshots</strong> and this will increase with the variations of tests you want to add for e.g. Unit test to check if the clear button clears the to-do Items.</p>
<h3 id="heading-what-cant-be-tested-using-snapshots">What can't be tested using snapshots?</h3>
<p><strong>But,</strong> there are a couple of <strong>things you may still not be able to test</strong> -</p>
<ul>
<li><p><strong>Functionalities which does not lead to DOM changes</strong> cannot be tested since they won't be captured in the snapshot.</p>
</li>
<li><p><strong>Functionalities which change DOM elements in the parent component</strong> (or any other component which is not a part of the component under test) cannot be tested since they won't be captured in the snapshot. The workaround for this would be to write the test in the parent.</p>
</li>
</ul>
<p>The easiest way to test this Todo App component would be to <strong>add a snapshot for the initial state of the component and other functionality can be tested using simple unit tests</strong> -</p>
<p><code>App.test.tsx</code></p>
<pre><code class="lang-typescript"><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> { fireEvent, render } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>;

describe(<span class="hljs-string">'&lt;App/&gt;'</span>, <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-comment">// snapshot test for capturing the initial state</span>
  it(<span class="hljs-string">'should match the snapshot'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> renderResult = render(&lt;App /&gt;);
    expect(renderResult.container).toMatchSnapshot();
  });

  <span class="hljs-comment">// other unit tests not using snapshot testing</span>
  it(<span class="hljs-string">'should add a todo item when clicked on add'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> renderResult = render(&lt;App /&gt;);
    <span class="hljs-keyword">const</span> inputElement = renderResult.getByTestId(<span class="hljs-string">'input'</span>);
    <span class="hljs-keyword">const</span> addButton = renderResult.getByText(<span class="hljs-string">'Add'</span>);
    fireEvent.change(inputElement, { target: { value : <span class="hljs-string">"Todo Item 1"</span>}});
    fireEvent.click(addButton);
    expect(renderResult.getByText(<span class="hljs-string">"Todo Item 1"</span>));
  });

  it(<span class="hljs-string">'should clear all todos when clicked on clear'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> renderResult = render(&lt;App /&gt;);
    <span class="hljs-keyword">const</span> inputElement = renderResult.getByTestId(<span class="hljs-string">'input'</span>);
    <span class="hljs-keyword">const</span> addButton = renderResult.getByText(<span class="hljs-string">'Add'</span>);
    <span class="hljs-keyword">const</span> clearButton = renderResult.getByText(<span class="hljs-string">'Clear'</span>);
    fireEvent.change(inputElement, { target: { value: <span class="hljs-string">"Todo Item 1"</span> } });
    fireEvent.click(addButton);

    fireEvent.click(clearButton)
    expect(renderResult.queryByText(<span class="hljs-string">"Todo Item 1"</span>)).toBeEmptyDOMElement;
  });
});
</code></pre>
<h3 id="heading-summary">Summary</h3>
<p>Now let's summarise the <strong>downsides of going ONLY for snapshot testing</strong> -</p>
<ul>
<li><p><strong>Events &amp; handlers methods code is not captured</strong> until they result in DOM changes in the same component.</p>
</li>
<li><p><strong>Additional files or snapshots are added to the repo</strong> if multiple variations of the test are needed.</p>
</li>
<li><p><strong>Merge conflicts will be a headache</strong> since every time we get a conflict we will have to resolve the merge conflict first, then regenerate the snapshot via tests, and then add it to the commit. so waste of time and energy.</p>
</li>
<li><p><strong>Code coverage</strong> if we are heavily relying on the snapshot tests - the code coverage may be good but it will not give enough confidence since internal workings on the component are not captured in the snapshot.</p>
</li>
<li><p><strong>Failures in snapshots are not paid much attention by the devs</strong> and they tend to directly update which is the biggest downside. additionally, it is <strong>difficult for the devs to figure out what went wrong</strong>.</p>
</li>
<li><p><strong>External Library updates</strong> - can cause the snapshots to change which will result in test failures and it will get difficult for the devs to identify the fix.</p>
</li>
<li><p>Increased number of Test Reruns - Especially to update the snapshots.</p>
</li>
</ul>
<p>because of all the above reasons, I feel you should <strong>only go for snapshot tests when the code results in a DOM change</strong> otherwise prefer normal unit tests. Additionally, In big projects, it is better not to have snapshot tests at all.</p>
<p>Feel free to share your thoughts in the comment section below.</p>
<p><mark>Thanks for reading!</mark></p>
]]></content:encoded></item><item><title><![CDATA[Multiple apps making your Macbook (intel chip) slow ? Try this.]]></title><description><![CDATA[During this summer when I was working on a project that required me to run IOS and Android simulators at the same time and on top of it screen sharing on…]]></description><link>https://blog.anoopjadhav.in/multiple-apps-making-your-macbook-intel-chip-slow-try-this</link><guid isPermaLink="true">https://blog.anoopjadhav.in/multiple-apps-making-your-macbook-intel-chip-slow-try-this</guid><category><![CDATA[macbook]]></category><category><![CDATA[heating issue]]></category><category><![CDATA[performance issue]]></category><category><![CDATA[slow machine]]></category><category><![CDATA[slow]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Sun, 25 Sep 2022 07:43:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680502153916/4d8ea680-27d7-4fb6-bf7b-69a514b4e9a5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>During this summer when I was working on a project that required me to run IOS and Android simulators at the same time and on top of it screen sharing on zoom literally made my macbook cry. </p>
<h3 id="heading-cmd-q">CMD + Q</h3>
<p> I talked to apple support about this problem and they suggested me to <strong>run fewer apps in parallel</strong> and <strong>quit all non required apps from memory</strong>(cmd + Q). for e.g. if your machine has 6 core then run only 6 apps in parallel including the background processes. Not sure of the internal workings, but for me this wasn't the solution.  </p>
<p>Check this by going to <em>Menu &gt; About my mac</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1664091860816/ZSOkWUztP.png" alt="Group 211.png" class="image--center mx-auto" /></p>
<h3 id="heading-activity-monitor">Activity Monitor</h3>
<p>Next step - we checked the activity monitor - the process called <strong>kernel task was hogging all the processing power</strong> and was slowing down the machine ever further. I realised that this <strong>kernel task kicks in whenever the machine starts heating up</strong>. </p>
<p>My colleagues who were working in an Air conditioned environment, their macbook performance was much better.  </p>
<h3 id="heading-turbo-boost">Turbo boost</h3>
<p>After googling a lot I read somewhere that there is a feature in mac with intel chips called <strong>Turbo boost</strong> which runs behind the scene and allows the mac processor to run at higher frequencies. </p>
<p>I installed a tool called <a target="_blank" href="http://tbswitcher.rugarciap.com/">Turbo boost switcher</a> and turned off the turbo boost feature. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1664091462060/21jFuR5k_.png" alt="Group 212.png" class="image--center mx-auto" /></p>
<p>This significantly improved the performance of my machine. I was able to work on multiple simulators without any heating issue. Please give this a try this may solve your problem too. </p>
<h3 id="heading-thanks">Thanks !</h3>
]]></content:encoded></item><item><title><![CDATA[[Part -2 ] Build & Publish React component as NPM package using Parcel]]></title><description><![CDATA[In the previous article we used typescript complier to build the react component. In this one we will see how to build it using parcel. Parcel is a zero…]]></description><link>https://blog.anoopjadhav.in/part-2-build-publish-react-component-as-npm-package-using-parcel</link><guid isPermaLink="true">https://blog.anoopjadhav.in/part-2-build-publish-react-component-as-npm-package-using-parcel</guid><category><![CDATA[parcel]]></category><category><![CDATA[React]]></category><category><![CDATA[Package Managers]]></category><category><![CDATA[npm]]></category><category><![CDATA[npm publish]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Tue, 20 Sep 2022 15:56:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680502243578/b8dabd70-cf88-41b9-aac1-22a7966ed518.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the <a target="_blank" href="https://creativedevs.hashnode.dev/part-1-build-publish-react-component-as-npm-package-using-typescript-compiler">previous article</a> we used typescript complier to build the react component. In this one we will see how to build it using parcel.</p>
<p><strong>Parcel</strong> is a zero configuration build tool. checkout their amazing website <a target="_blank" href="https://parceljs.org/">here</a>.</p>
<p>It is pretty easy to setup a project using parcel. since we are building an independent react component we need to <a target="_blank" href="https://parceljs.org/getting-started/library/">build it as a library</a>.</p>
<p>Now let's go through the steps to build the project -</p>
<ul>
<li>**Install Parcel **</li>
</ul>
<pre><code class="lang-plaintext">npm install --save-dev parcel @parcel/transformer-typescript-types @parcel/packager-ts
</code></pre>
<p>or</p>
<pre><code class="lang-plaintext">yarn add -D parcel @parcel/transformer-typescript-types @parcel/packager-ts
</code></pre>
<ul>
<li>**Add build script to package.json **</li>
</ul>
<p>This will build your project and export the files in the specified directory ( dist/ in this case ).</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"parcel build"</span>
}
</code></pre>
<ul>
<li>**Update source, module, types paths in package.json **</li>
</ul>
<pre><code class="lang-json">{
  <span class="hljs-attr">"source"</span>: <span class="hljs-string">"./src/index.ts"</span>, <span class="hljs-comment">// path to starting point in library</span>
  <span class="hljs-attr">"module"</span>: <span class="hljs-string">"./dist/index.js"</span>, <span class="hljs-comment">// output directory path i.e dist</span>
  <span class="hljs-attr">"types"</span>: <span class="hljs-string">"./dist/index.d.ts"</span>, <span class="hljs-comment">// path where the types will be exported</span>
}
</code></pre>
<p><strong>module</strong> tells parcel that the output will be an es module.</p>
<p>now your package.json should look like -</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"react-toggle-button"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.0.1"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"React toggle button"</span>,
  <span class="hljs-attr">"source"</span>: <span class="hljs-string">"./src/index.ts"</span>,
  <span class="hljs-attr">"module"</span>: <span class="hljs-string">"./dist/index.js"</span>,
  <span class="hljs-attr">"types"</span>: <span class="hljs-string">"./dist/index.d.ts"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"parcel build"</span> <span class="hljs-comment">// command to build the project</span>
  },
  <span class="hljs-attr">"repository"</span>: {
    <span class="hljs-attr">"type"</span>: <span class="hljs-string">"git"</span>,
    <span class="hljs-attr">"url"</span>: <span class="hljs-string">"git+https://github.com/YOUR-REPO/react-toggle-button.git"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [
    <span class="hljs-string">"react"</span>,
    <span class="hljs-string">"react-toggle-button"</span>
  ],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"AUTHOR NAME"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>,
  <span class="hljs-attr">"bugs"</span>: {
    <span class="hljs-attr">"url"</span>: <span class="hljs-string">"https://github.com/YOUR-REPO/react-toggle-button/issues"</span>
  },
  <span class="hljs-attr">"homepage"</span>: <span class="hljs-string">"https://github.com/YOUR-REPO/react-toggle-button#readme"</span>,
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"@parcel/packager-ts"</span>: <span class="hljs-string">"2.7.0"</span>,
    <span class="hljs-attr">"@parcel/transformer-typescript-types"</span>: <span class="hljs-string">"2.7.0"</span>,
    <span class="hljs-attr">"@types/react"</span>: <span class="hljs-string">"^18.0.18"</span>,
    <span class="hljs-attr">"@types/react-dom"</span>: <span class="hljs-string">"^18.0.6"</span>,
    <span class="hljs-attr">"parcel"</span>: <span class="hljs-string">"^2.7.0"</span>,
    <span class="hljs-attr">"react"</span>: <span class="hljs-string">"^18.2.0"</span>,
    <span class="hljs-attr">"react-dom"</span>: <span class="hljs-string">"^18.2.0"</span>,
    <span class="hljs-attr">"typescript"</span>: <span class="hljs-string">"^4.8.3"</span>
  },
  <span class="hljs-attr">"peerDependencies"</span>: {
     <span class="hljs-attr">"react"</span>: <span class="hljs-string">"^18.2.0"</span> <span class="hljs-comment">// add react as a peer dependency</span>
  },
  <span class="hljs-attr">"files"</span>: [
    <span class="hljs-string">"/dist"</span> <span class="hljs-comment">// tells the bundler to only add dist folder while publishing the package. package.json will be automatically added. </span>
  ]
}
</code></pre>
<p>you can <strong>remove tsc-hooks from package.json and tsconfig.json</strong> (<a target="_blank" href="https://creativedevs.hashnode.dev/part-1-build-publish-react-component-as-npm-package-using-typescript-compiler">added in part 1</a>) since parcel will take care of all the css bundling and will export it to dist directory.</p>
<ul>
<li>**Build the project **</li>
</ul>
<p>This will bundle your react component and export the files in the dist directory. These are the files which we want to publish as a package.</p>
<pre><code class="lang-plaintext">npm run build
</code></pre>
<ul>
<li><strong>Update .npmignore</strong></li>
</ul>
<p>This is to ignore .parcel-cache directory while publishing the package.</p>
<pre><code class="lang-plaintext">/src
/.parcel-cache
</code></pre>
<ul>
<li>**Publish **</li>
</ul>
<p>Now you can update the package version and publish your package.</p>
<pre><code class="lang-plaintext">npm publish
</code></pre>
<p>**Thanks ! **</p>
]]></content:encoded></item><item><title><![CDATA[Switch to Dark Mode using Only CSS variables]]></title><description><![CDATA[Switch to Dark Mode using Only CSS variables]]></description><link>https://blog.anoopjadhav.in/switch-to-dark-mode-using-only-css-variables</link><guid isPermaLink="true">https://blog.anoopjadhav.in/switch-to-dark-mode-using-only-css-variables</guid><category><![CDATA[darkmode]]></category><category><![CDATA[CSS]]></category><category><![CDATA[css variables]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Design]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Mon, 19 Sep 2022 09:15:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680502285472/8fe39041-b11c-4af3-a14b-4a7c812c53c1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The easiest way to implement dark mode in your website or portfolio apps is by using CSS variables. In my portfolio app I relied on CSS variables to switch between dark &amp; light mode. </p>
<p>I implemented this using SCSS as a commonStyle library for <a target="_blank" href="https://anoopjadhav.vercel.app">my personal portfolio</a>. But a simplified version in CSS would look as below - </p>
<p>/theme.css</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-comment">/* grey values */</span>
  <span class="hljs-attribute">--grey1</span>: <span class="hljs-number">#212122</span>; <span class="hljs-comment">/* darkest */</span>
  <span class="hljs-attribute">--grey2</span>: <span class="hljs-number">#333333</span>;
  <span class="hljs-attribute">--grey3</span>: <span class="hljs-number">#828282</span>;
  <span class="hljs-attribute">--grey4</span>: <span class="hljs-number">#bdbdbd</span>;
  <span class="hljs-attribute">--grey5</span>: <span class="hljs-number">#e0e0e0</span>;
  <span class="hljs-attribute">--grey6</span>: <span class="hljs-number">#f2f2f2</span>;
  <span class="hljs-attribute">--grey7</span>: white; <span class="hljs-comment">/* lightest */</span>

  <span class="hljs-attribute">--red</span>: <span class="hljs-number">#eb5757</span>;

  <span class="hljs-comment">/* banner colors */</span>
  <span class="hljs-attribute">--orange</span>: <span class="hljs-number">#f2994a</span>;
  <span class="hljs-attribute">--yellow</span>: <span class="hljs-number">#f2c94c</span>;
  <span class="hljs-attribute">--green</span>: <span class="hljs-number">#27ae60</span>;

  <span class="hljs-comment">/* primary &amp; accent color */</span>
  <span class="hljs-attribute">--primary-color</span>: <span class="hljs-built_in">var</span>(--red);
  <span class="hljs-attribute">--accent-color</span>: <span class="hljs-built_in">var</span>(--orange);

  <span class="hljs-comment">/* use variables to set colors as follows - */</span>
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">var</span>(--grey7);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--grey1);
}

<span class="hljs-comment">/* reverse the color values for darkmode*/</span>
<span class="hljs-selector-tag">body</span><span class="hljs-selector-class">.darkmode</span> {
  <span class="hljs-attribute">--grey1</span>: white; <span class="hljs-comment">/* lightest */</span>
  <span class="hljs-attribute">--grey2</span>: <span class="hljs-number">#f2f2f2</span>; 
  <span class="hljs-attribute">--grey3</span>: <span class="hljs-number">#e0e0e0</span>;
  <span class="hljs-attribute">--grey4</span>: <span class="hljs-number">#bdbdbd</span>;
  <span class="hljs-attribute">--grey5</span>: <span class="hljs-number">#828282</span>;
  <span class="hljs-attribute">--grey6</span>: <span class="hljs-number">#333333</span>;
  <span class="hljs-attribute">--grey7</span>: <span class="hljs-number">#212122</span>; <span class="hljs-comment">/* darkest */</span>
}
</code></pre>
<p>The color values will switch as soon as you append darkmode class to the body element. </p>
<p>here is the VS code + color highlight plugin version of the same code - 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663579010575/v3KB5tOSs.png" alt="Screenshot 2022-09-19 at 2.46.26 PM.png" /></p>
<p>The only pending part now is to append the <strong>darkmode</strong> class to the body when you <strong>click on the darkmode toggle button</strong>.  In JS you can use - </p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toggleButtonHandler</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">document</span>.body.classList.toggle(<span class="hljs-string">'darkmode'</span>);
}
</code></pre>
<p><strong>Thanks ! </strong></p>
]]></content:encoded></item><item><title><![CDATA[[Part 1] - Build & Publish React component as NPM package using Typescript compiler]]></title><description><![CDATA[Publish React, Typescript, CSS component as NPM package (No Webpack required)]]></description><link>https://blog.anoopjadhav.in/part-1-build-publish-react-component-as-npm-package-using-typescript-compiler</link><guid isPermaLink="true">https://blog.anoopjadhav.in/part-1-build-publish-react-component-as-npm-package-using-typescript-compiler</guid><category><![CDATA[React]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[CSS]]></category><category><![CDATA[npm]]></category><category><![CDATA[npm publish]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Fri, 09 Sep 2022 12:58:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680502323468/b83337d6-0fd5-4d4e-90a1-5176f094293d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I was too <strong>lazy to include webpack</strong> to bundle the react component as it needs a lot of boilerplate configuration code. so easiest way was to build the react typescript project using the typescript compiler with a little help from tsc-hooks.</p>
<p>you can follow the steps to know more about building and publishing a react project without the use of webpack.</p>
<h4 id="heading-lets-first-initialise-the-project">Let's first initialise the project.</h4>
<pre><code class="lang-plaintext">mkdir toggle-button

yarn init
or 
npm init
</code></pre>
<h4 id="heading-add-the-following-packages-as-dev-dependencies">Add the following packages as dev dependencies-</h4>
<pre><code class="lang-plaintext">yarn add -D react react-dom @types/react @types/react-dom typescript tsc-hooks
or 
npm install --save-dev react react-dom @types/react @types/react-dom typescript tsc-hooks
</code></pre>
<p>Update <strong>react</strong> as <strong>peer dependency</strong> so that the user of this package will be <strong>prompted</strong> to install react while adding this package.</p>
<p>now the <strong>package.json</strong> should look like -</p>
<p>package.json</p>
<pre><code class="lang-plaintext">{
  "name": "react-toggle-button",
  "version": "0.0.1",
  "description": "React toggle button",
  "main": "dist/", // update this
  "scripts": {
    "test": "yarn test",
    "build": "tsc" // runs tsc compiler to build the project in dist directory (configured in tsconfig.json)
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/YOUR-REPO/react-toggle-button.git"
  },
  "keywords": [
    "react",
    "react-toggle-button"
  ],
  "author": "AUTHOR NAME",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/YOUR-REPO/react-toggle-button/issues"
  },
  "homepage": "https://github.com/YOUR-REPO/react-toggle-button#readme",
  "devDependencies": {
    "@types/react": "^18.0.18",
    "react": "^18.2.0",
    "tsc-hooks": "^1.1.1", // needed to copy css files in the final build
    "typescript": "^4.8.3"
  },
  "peerDependencies": {
     "react": "^18.2.0" // add react as a peer dependency
  },
  "files": [
    "/dist" // tells the bundler to only add dist folder while publishing the package. package.json will be automatically added. 
  ]
}
</code></pre>
<h4 id="heading-add-tsconfigjson">Add tsconfig.json</h4>
<p>now let's add <strong>tsconfig.json</strong> for the typescript compiler to know where and how to build the typescript files.</p>
<p>tsconfig.json</p>
<pre><code class="lang-plaintext">{
    "compilerOptions": {
        "target": "ES2015",
        "jsx": "react",
        "module": "esnext",
        "moduleResolution": "node",
        "allowJs": true,
        "declaration": true, // required to generate corresponding *.d.ts files
        "outDir": "./dist",
        "esModuleInterop": true,
        "strict": true,
        "noImplicitAny": true,
    },
    "exclude": [
        "node_modules",
    ],
    "hooks": [
        "copy-files" // copies all files to the dist folder
    ],
    "include": [
        "src/",
        "src/**/*.module.css" // include css files while building the project using tsc
    ]
}
</code></pre>
<p>if you want to avoid copying all files to the final build then another workaround is to use a package <a target="_blank" href="https://www.npmjs.com/package/copyfiles"><strong>copyfiles</strong></a> and add a script in package.json to manually copy selective files. For eg. In this case we are copying all css files.</p>
<p>package.json</p>
<pre><code class="lang-json">...
 <span class="hljs-string">"copy-files"</span>: <span class="hljs-string">"copyfiles -u 1 src/**/*.css dist/"</span>,
...
</code></pre>
<h4 id="heading-add-npmignore">Add .npmignore</h4>
<p>Add <strong>.npmignore</strong> to exclude src files from the final npm package build.</p>
<p>.npmignore</p>
<pre><code class="lang-plaintext">/src
</code></pre>
<p>Now lets add the react component in the <strong>src</strong> directory</p>
<p>src/ToggleButton/ToggleButton.tsx</p>
<pre><code class="lang-plaintext">import React from "react";
import styles from "./ToggleButton.module.css";
interface ToggleButtonProps {
  onClick: () =&gt; void;
  value: boolean;
}
const ToggleButton = ({ onClick, value }: ToggleButtonProps) =&gt; {
  function clickHandler() {
    onClick();
  }
  return (
    &lt;div
      id={value ? "on" : "off"}
      className={styles.toggleButton}
      onClick={clickHandler}
    &gt;
      &lt;div className={styles.bar}&gt;
        &lt;div className={styles.circle}&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

export default ToggleButton;
</code></pre>
<p>src/ToggleButton/ToggleButton.module.css</p>
<pre><code class="lang-plaintext">.toggleButton {
  position: relative;
  width: 36px;
  height: 1rem;
  display: flex;
  align-items: center;
}
.circle {
  width: 17px;
  height: 17px;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  transition: all 0.3s ease-in;
  --on : #eb5757;
  --off: #e0e0e0;
}
.bar {
  height: 20px;
  width: 100%;
  border-radius: 50px;
  padding: 2px;
}
#on .bar {
  background-color: var(--on);
}
#off .bar {
  background-color: var(--off);
}
#on .circle {
  background-color: var(--on);
  left: calc(100% - 19px);
}
#off .circle {
  background-color: var(--off);
  left: 2px;
}
</code></pre>
<h4 id="heading-add-declarationsdts">Add declarations.d.ts</h4>
<p>Add <strong>declarations.d.ts</strong> file so that typescript compliler know about the *.module.css files.</p>
<p>src/declarations.d.ts</p>
<pre><code class="lang-plaintext">declare module '*.module.css' {
  const classes: { [key: string]: string };
  export default classes;
}
</code></pre>
<p>Directory structure should look like -</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662725868000/O-zXoLs2z.png" alt="Screenshot 2022-09-09 at 5.46.46 PM.png" /></p>
<h4 id="heading-add-readme-file">Add Readme file</h4>
<p>Don't forget to add a README.md file in the root directory with all the installation and usage of the package you are deploying. I am skipping this step in the example.</p>
<h4 id="heading-build-package-andamp-publish">Build package &amp; Publish</h4>
<p>Lets run tsc compiler to generate the respective files in dist directory -</p>
<pre><code class="lang-plaintext">yarn build // spits the output files in the dist/ directory
</code></pre>
<p>now we are ready to publish the package. If you are deploying for the first time - create an npm account and login in the terminal.</p>
<pre><code class="lang-plaintext">npm login // skip this if you are already logged in
npm publish
</code></pre>
<p>Update the package version before every publish otherwise the publish will fail.</p>
<h3 id="heading-thanks">Thanks</h3>
]]></content:encoded></item><item><title><![CDATA[Thinking accessibility while choosing charting libraries]]></title><description><![CDATA[Thinking accessibility while choosing charting libraries]]></description><link>https://blog.anoopjadhav.in/thinking-accessibility-while-choosing-charting-libraries</link><guid isPermaLink="true">https://blog.anoopjadhav.in/thinking-accessibility-while-choosing-charting-libraries</guid><category><![CDATA[Accessibility]]></category><category><![CDATA[Web Accessibility]]></category><category><![CDATA[charts]]></category><category><![CDATA[amChart]]></category><category><![CDATA[highcharts]]></category><dc:creator><![CDATA[Anoop Jadhav]]></dc:creator><pubDate>Fri, 24 Jun 2022 12:25:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680502372050/2310b126-46a5-44bc-83a9-5c218f7898ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While choosing a charting library we can think of the following parameters to improve the overall accessibility -</p>
<ol>
<li><p>Colour contrast ratio</p>
</li>
<li><p>Arial labels / Title / Label/ Description</p>
</li>
<li><p>Simpler charts or tables</p>
</li>
<li><p>Providing text summary of complex charts</p>
</li>
<li><p>Ease of interacting with data elements</p>
</li>
<li><p>Prefer prefers-reduced-motion css media feature</p>
</li>
<li><p>Responsive design</p>
</li>
</ol>
<h3 id="heading-1-colour-contrast-ratio">**1. Colour contrast ratio **</h3>
<blockquote>
<p>Contrast ratio is a term that’s used to measure the difference between the maximum and minimum brightness of a display. In simple terms the better the ratio the easier it is to differentiate those colours.</p>
</blockquote>
<p>Depending on the <a target="_blank" href="https://www.w3.org/WAI/standards-guidelines/wcag/">accessibility level</a> you can choose contrasting colours for the chart elements. There are several tools available to check the CCR ratio.</p>
<p>for e.g. <a target="_blank" href="https://contrast-ratio.com">https://contrast-ratio.com</a></p>
<h3 id="heading-2-aria-labels-title-label-description">**2. Aria Labels, Title, Label, Description **</h3>
<p>Prefer adding meaningful <a target="_blank" href="https://www.w3.org/WAI/GL/WCAG20-TECHS/aria">Arial tags</a>/title/labels/description to the elements which is necessary to be read by the screen reader. you can check if the elements are being correctly read by using the following screen readers - JAWS, Voice Over(IOS), NVDA</p>
<h3 id="heading-3-simpler-charts-or-tables"><strong>3. Simpler charts or tables</strong></h3>
<p>There will be scenarios where you might have to choose between charts. In such situations always prefer simpler charts with fewer UI elements. for simpler datasets preferably go for <a target="_blank" href="https://webaim.org/techniques/tables/">data tables</a>.</p>
<h3 id="heading-4-providing-text-summary-for-complex-charts"><strong>4. Providing text summary for complex charts</strong></h3>
<p>If it is extremely necessary to have a complex chart then in such scenarios always provide a gist of the value provided by the chart either as a label or description. Nowadays most charting libraries allow developers to add labels and descriptions to the data elements as well.</p>
<p>For example, in <a target="_blank" href="https://www.chartjs.org/docs/latest/general/accessibility.html">chart.js</a> you can provide arial-label, and role.</p>
<pre><code class="lang-plaintext">&lt;canvas id="goodCanvas1" width="400" height="100" aria-label="Hello ARIA World" role="img"&gt;&lt;/canvas&gt;
</code></pre>
<h3 id="heading-5-ease-of-interacting-with-data-elements"><strong>5. Ease of interacting with data elements</strong></h3>
<p>In a web application, the ease of navigating through the UI elements using the keyboard is quite an important factor for accessibility. Similarly in charts, the user should be able to navigate through the chart elements using the keyboard.</p>
<p>To understand this better let's check the type of charting libraries available -</p>
<ul>
<li><p>SVG-based - creates DOM elements for charts which are focusable by keyboard with modification like adding tab-index. Although adding tab-index at runtime is difficult and tedious. so preferably go for a library like Highcharts or amCharts which has out-of-the-box support to add focusable elements.</p>
</li>
<li><p>Canvas-based - uses Canvas API to draw chart elements. so keyboard navigation will be difficult but there are a few libraries like <a target="_blank" href="https://www.amcharts.com/docs/v5/concepts/accessibility/">amChart version 5</a> which allow keyboard navigation to predefined focusable elements.</p>
</li>
</ul>
<h3 id="heading-6-prefer-prefers-reduced-motion-css-media-feature"><strong>6. Prefer prefers-reduced-motion css media feature</strong></h3>
<blockquote>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion">prefers-reduced-motion</a> CSS media feature is used to detect if the user has requested that the system minimize the amount of non-essential motion it uses.</p>
</blockquote>
<p>Animations on charts may be a distraction for some specially-abled users, so it's always good to use this media feature to remove or reduce the animations on charts.</p>
<h3 id="heading-7-responsive-design"><strong>7. Responsive design</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660753215582/Hvww10_H-.gif" alt="responsive-new.gif" class="image--center mx-auto" /></p>
<p>Keeping the charts responsive will help the user gain the same value on any device. Most libraries these days support responsive design.</p>
<h3 id="heading-libraries">Libraries</h3>
<p><strong><em>Following are the few popular charting libraries available which have good to basic support for accessibility -</em></strong></p>
<ul>
<li><a target="_blank" href="https://www.highcharts.com/">Highcharts</a></li>
</ul>
<p>SVG-based, Paid, <a target="_blank" href="https://www.highcharts.com/blog/accessibility/">Good accessibility support is available</a></p>
<ul>
<li><a target="_blank" href="https://www.amcharts.com/">AmCharts</a></li>
</ul>
<p>version 4- SVG based, Paid, <a target="_blank" href="https://www.amcharts.com/docs/v4/concepts/accessibility/">Good accessibility support available</a></p>
<p>version 5 - Canvas based, Paid, <a target="_blank" href="https://www.amcharts.com/docs/v5/concepts/accessibility/">Good accessibility support available</a></p>
<ul>
<li><a target="_blank" href="https://www.chartjs.org/">Chart.js</a></li>
</ul>
<p>Canvas-based, free, <a target="_blank" href="https://www.chartjs.org/docs/latest/general/accessibility.html">Very Basic accessibility support is available</a></p>
<ul>
<li><a target="_blank" href="https://d3js.org/">D3.js</a></li>
</ul>
<p>SVG based, free, No out of the box support for accessibility but possible to improve by adding labels and having a good CCR ratio. <a target="_blank" href="https://fossheim.io/writing/posts/accessible-dataviz-d3-intro/">click this to know more.</a></p>
<p>Feel free to comment if any feedback or concerns. Thanks !</p>
]]></content:encoded></item></channel></rss>