<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ankit Saxena on Medium]]></title>
        <description><![CDATA[Stories by Ankit Saxena on Medium]]></description>
        <link>https://medium.com/@ankit-saxena2605?source=rss-c5913db1e0bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_HeSsoI9Hd-ZijlO</url>
            <title>Stories by Ankit Saxena on Medium</title>
            <link>https://medium.com/@ankit-saxena2605?source=rss-c5913db1e0bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:39:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankit-saxena2605/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction to Web Components in JavaScript: Create a Hello-World Web Component]]></title>
            <link>https://javascript.plainenglish.io/introduction-to-web-components-in-javascript-create-a-hello-world-web-component-e624874ec3b1?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e624874ec3b1</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Fri, 23 Sep 2022 09:48:24 GMT</pubDate>
            <atom:updated>2022-09-27T14:07:44.336Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial on how to create a Hello-World web component using JavaScript.</h4><p>Web Components is a suite of different technologies allowing you to create reusable custom HTML elements. What makes it great is the encapsulation of the component’s logic and styles. We can keep an element’s features private, so they can be scripted and styled without the fear of collision with other parts of the document.</p><p>Web Components consist of three main technologies:</p><ul><li><strong>Custom elements</strong>: A set of JavaScript APIs that allow you to define new custom HTML tags or improve existing ones.</li></ul><pre>class MyComponent extends HTMLElement {<br>  constructor() {<br>    super();<br>    this.innerHTML = `&lt;p&gt;My Web Component&lt;/p&gt;`;<br>  }<br>}<br>    <br>customElements.define(&#39;my-component&#39;, MyComponent);</pre><ul><li><strong>Shadow DOM: </strong>A set of JavaScript APIs for attaching an encapsulated “shadow” DOM tree to an element that is rendered separately from the main document DOM. Shadow DOM ensures that the styles or JavaScript we define for our web component will not leak out and affect other parts of the application.<br>You can attach a shadow root to any element using the Element.attachShadow() method.</li></ul><pre>const shadow = this.attachShadow({mode: &#39;open&#39;});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*4bvf4SBwrUA6vjbSY6o-Xw.png" /></figure><ul><li><strong>HTML templates:</strong> A template allows you to define HTML in your page that your web component can use. The template and its contents are not rendered in the DOM but can still be referenced using JavaScript. <br><strong>Note</strong>: There is also the &lt;slot&gt; element which you can use to manage the content of an element.</li></ul><h3>Life cycle methods</h3><p>The browser automatically calls six methods throughout the lifecycle of the Web Component state.</p><ol><li><strong>constructor()</strong>: It is called when the component is initialised. It must call super() and can set any defaults or perform other pre-rendering processes.</li><li><strong>connectedCallback()</strong>: Invoked when the custom element is first connected to the document’s DOM.</li><li><strong>disconnectedCallback()</strong>: Invoked when the custom element is disconnected from the document’s DOM.</li><li><strong>adoptedCallback()</strong>: This function is called when a Web Component is moved from one document to another.</li><li><strong>attributeChangedCallback()</strong>: Invoked when one of the custom element’s attributes is added, removed, or changed.</li><li><strong>static observedAttributes()</strong>: Returns an array of attributes that the browser will observe.</li></ol><h3>Creating a &lt;/hello-world&gt; web component:</h3><h3>Custom elements</h3><p>We need to define a class to control the element. It can be named anything, let’s call it HelloWorld. It must extend the HTMLElement interface, which represents the default properties and methods of every HTML element.</p><pre>class HelloWorld extends HTMLElement {<br>  constructor() {<br>    super();<br>    this.textContent = &#39;Hello World!&#39;;<br>  }<br>}</pre><p>The class must be registered with the CustomElementRegistry to define it as a handler for a specific element. The name must contain a dash to never clash with elements officially supported in the HTML specification.</p><pre>customElements.define( &#39;hello-world&#39;, HelloWorld );</pre><h3>Adding Attributes</h3><p>As of now our component is only printing hello world on the screen. To make the greeting dynamic we can add HTML attributes:</p><pre>&lt;hello-world name=&quot;Ankit&quot;&gt;&lt;/hello-world&gt;</pre><p>And the textContent will change as follows:</p><pre>class HelloWorld extends HTMLElement {<br>  constructor() {<br>    super();<br>    this.textContent = `Hello ${this.getAttribute(&quot;name&quot;)}!`;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrcVrBo4aOQOA5QzdSV1yg.png" /></figure><h3>Shadow Dom</h3><p>While the Web Component we’ve built above works, it’s not immune to outside interference, and CSS or JavaScript could modify it. The styles we define for our component can leak out and affect other parts of the document. To prevent that we need to create a shadow dom. The Shadow DOM solves this encapsulation problem by attaching a separated DOM to the Web Component. The Shadow DOM can be manipulated like any other DOM element.</p><pre>this.shadow = this.attachShadow({ mode: &quot;open&quot; });</pre><ul><li>{ mode: “open” } — It means that we can access the shadow DOM using JavaScript written in the main page context using the Element.shadowRoot property.</li><li>{ mode: “closed” } — It means the Shadow DOM can only be accessed within the Web Component. If you attach a shadow root to a custom element with { mode: “closed”}, you won’t be able to access the shadow DOM from the outside i.e Element.shadowRoot will return null.</li></ul><h3>HTML templates:</h3><p>Here we can define the HTML and CSS for our web component.</p><pre>const template = document.createElement(&quot;template&quot;);<br>template.innerHTML = `<br>  &lt;style&gt;<br>     .hello-world h1 {<br>      font-weight: bold;<br>      font-family: sans-serif;<br>      color: red;<br>    }<br>  &lt;/style&gt;<br>  &lt;div class=&quot;hello-world&quot;&gt;<br>  &lt;h1&gt;Hello &lt;span id=&quot;name&quot;&gt;&lt;/span&gt;!&lt;/h1&gt; <br>  &lt;/div&gt;<br>`;</pre><p>Updating the constructor to attach our template to the shadow DOM and setting the initial value of name as “World”:</p><pre>constructor() {<br>    super();<br>    this.shadow = this.attachShadow({ mode: &quot;open&quot; });<br>    this.shadowRoot.appendChild(template.content.cloneNode(true));<br>    this.shadowRoot.querySelector(&quot;#name&quot;).innerText = &quot;World&quot;;<br>  }</pre><p>Now we can also use the observedAttributes and attributeChangedCallback methods to update the name when our web component is added to the DOM.</p><pre>static get observedAttributes() {<br>    return [&quot;name&quot;];<br>  }<br>attributeChangedCallback(property, oldValue, newValue) {<br>    if (oldValue === newValue) return;<br>    this[property] = newValue;<br>  }<br>connectedCallback() {<br>    this.shadowRoot.querySelector(&quot;#name&quot;).innerText = this.name;<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai9SMt2pTGIDvCQ7h0sphg.gif" /></figure><p>Full JS code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3408f3906f446a92afd9670505ffb446/href">https://medium.com/media/3408f3906f446a92afd9670505ffb446/href</a></iframe><p>Full Code: <a href="https://codepen.io/AnkitSaxena2605/pen/dyeNYNN?editors=1010">Codepen Demo</a></p><p>More web components examples :</p><ol><li>Counter: <a href="https://codepen.io/AnkitSaxena2605/pen/OJZgOdg">Codepen Demo</a></li><li>Edit word: <a href="https://codepen.io/AnkitSaxena2605/pen/GRdEOzr">Codepen Demo</a></li></ol><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e624874ec3b1" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/introduction-to-web-components-in-javascript-create-a-hello-world-web-component-e624874ec3b1">Introduction to Web Components in JavaScript: Create a Hello-World Web Component</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Web Workers in JavaScript With Real-World Example]]></title>
            <link>https://javascript.plainenglish.io/understanding-web-workers-in-js-with-real-world-example-1629a283aeec?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1629a283aeec</guid>
            <category><![CDATA[web-workers-in-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Sat, 28 May 2022 10:34:34 GMT</pubDate>
            <atom:updated>2022-05-31T01:48:40.532Z</atom:updated>
            <content:encoded><![CDATA[<h4>What are web workers in JavaScript? Explained with a real-world example.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DEmR3-q141lAMli0" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JavaScript is a single-threaded programming language. That means everything happens on that single main thread. It can’t do multiple things at the same time. <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Web workers</a> were introduced to solve this issue. Web workers give us the possibility to write multi-threaded JavaScript, which does not block the DOM. Even the Asynchronous operations block the DOM to some extent.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Web workers</a> cannot perform any kind of DOM manipulation as it does not have access to the Window object, the Document Object, or the DOM. However it does have access to the location object, the navigator object, fetch, the Application Cache, and importing external scripts using importScripts().</p><h4>Syntax :</h4><p>Below is the syntax to create a new instance of a worker. The worker constructor takes a path to a worker script (i.e worker.js).</p><pre>var myWorker = new Worker(&#39;worker.js&#39;);</pre><h4>Sending messages to a web worker</h4><p>We can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage">postMessage()</a> method and the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker/message_event">onmessage</a> event handler to send data from the main thread to the worker file and vice versa. The data is copied rather than shared i.e you can pass objects over and copies get made of those objects.</p><p><strong>Sending data from the main thread to the worker:</strong></p><pre>worker.postMessage(&#39;Hello&#39;);</pre><p>Adding onmessage event listener for our worker.</p><pre>worker.onmessage = function(e) {<br>   let data = ev.data;<br>   console.log(data);<br>}</pre><p><strong>Sending data from a web worker:</strong></p><p>Inside our worker.js file, we can use <strong>self.onmessage</strong> and <strong>self.postMessage</strong> to receive and send data to the parent thread.</p><pre>self.onmessage = (e) =&gt; {<br> if(e.data !== undefined) {<br>        var msg = e.data + &#39; World&#39;;<br>        // Posting back to the page<br>        self.postMessage(msg)<br>    }<br>});</pre><h4>Real-World Example:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJ8yLdnJmil6M5JFgkr8rw.gif" /></figure><p>Here we have a simple HTML page with some animation on it and a button (calculate sum) to perform a heavy operation. On clicking this button we are performing a sum calculation from 0 to 1000000000.</p><pre>let sum = 0;<br>for (let i = 0; i &lt; 1000000000; i++) {<br>    sum += i;<br>}<br>alert(sum);</pre><p>As we click on this button the animation will freeze because our main thread is busy in performing that complex calculation. And the animation will continue only when that calculation is complete. So here come web workers to the rescue. We can provide this complex calculation task to a web worker as shown below:</p><p><strong>In app.js</strong></p><pre>document.getElementById(&#39;sumBtn&#39;).addEventListener(&#39;click&#39;, ()=&gt; {<br>      worker.postMessage({&#39;do&#39;:&#39;Sum&#39;})<br>});</pre><p><strong>In worker.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e305c6cbad21ee6d5936e555354e3635/href">https://medium.com/media/e305c6cbad21ee6d5936e555354e3635/href</a></iframe><p>The result is shown in the below gif. Now the animation is not stopping on clicking the button as the complex calculation task is now being handled by the web worker in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKAXi3ZkwyRFWXb4f99d6Q.gif" /></figure><h3>Shared Workers:</h3><p>A dedicated worker is accessible and connected to only one single script and cannot post messages to other scripts or workers. A <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#shared_workers">shared worker</a> on the other hand is accessible by multiple scripts — even if they are being accessed by different windows, iframes, or even workers.</p><h4>Syntax:</h4><pre>var myWorker = new SharedWorker(&#39;worker.js&#39;);</pre><h4>Sending data to a shared worker</h4><p>For a shared worker we have to communicate via a port object — an explicit port is opened that the scripts can use to communicate with the worker. This port connection will implicitly start with the use of the <strong>onmessage</strong> event handler.<br>So instead of using <strong>myWorker.postMessage()</strong> we have to use <strong>myWorker.port.postMessage()</strong>.</p><pre>document.getElementById(&#39;sumBtn&#39;).addEventListener(&#39;click&#39;, ()=&gt; {<br>      myWorker.port.postMessage({&#39;do&#39;:&#39;Sum&#39;})<br>});</pre><p><strong>Note:</strong> Need to use the start() method if you are using addEventListener() method for onmessage event.</p><h4>Sending data from a shared worker</h4><p>Here the approach is a bit different compared to a web worker. First, we use an <strong>onconnect</strong> handler to fire code when a connection to the port happens (i.e. when the <strong>onmessage</strong> event handler in the parent thread is set up, or when the start() method is explicitly called in the parent thread). Next, we add an onmessage handler on the port to do the calculation and return the result to the main thread.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a86f202363dd838662ede59582501c0/href">https://medium.com/media/3a86f202363dd838662ede59582501c0/href</a></iframe><p><strong>Note:</strong> If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).</p><h4>Full Source Code:</h4><p><strong>Web Workers example: </strong><a href="https://github.com/ankitsaxena21/Web-Workers-Demo">Github Repo Link</a><strong><br>Shared Workers example: </strong><a href="https://github.com/ankitsaxena21/Shared-Worker">Github Repo Link</a></p><h4>Video Explanation:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3zx7DmJIAho&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3zx7DmJIAho&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb8c82ceb25634d05705d7aabdea7ba6/href">https://medium.com/media/cb8c82ceb25634d05705d7aabdea7ba6/href</a></iframe><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Check out our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Community Discord</em></strong></a><em> and join our </em><a href="https://inplainenglish.pallet.com/talent/welcome"><strong><em>Talent Collective</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1629a283aeec" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-web-workers-in-js-with-real-world-example-1629a283aeec">Understanding Web Workers in JavaScript With Real-World Example</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write polyfills for the call(), apply(), and bind() methods in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/writing-polyfills-for-call-apply-and-bind-methods-in-javascript-13b4ba313273?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/13b4ba313273</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Sat, 09 Apr 2022 09:44:24 GMT</pubDate>
            <atom:updated>2024-07-24T18:49:00.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q0xvXSgqWh0ljzKL" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The call(), apply() and bind() methods are used for function borrowing in JavaScript. It means that by using them, we can use the methods of one object on a different object without having to make a copy of that method and maintain it in two separate places.</p><p>Let’s say we have an object <strong>myName</strong> with properties <strong>firstName</strong> &amp; <strong>lastName</strong> and a function <strong>printName()</strong> that prints the firstName and lastName as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/478d7af6df19b10597bef14db7e2271d/href">https://medium.com/media/478d7af6df19b10597bef14db7e2271d/href</a></iframe><p>We want to borrow the<strong> </strong><strong>printName()</strong> function to print the firstName and lastName properties of the <strong>myName</strong> object. Let’s understand how it can be done using the call(), apply() and bind() <a href="https://www.youtube.com/watch?v=ixLo_7qggm0">methods</a>.</p><blockquote><em>💡 </em>Speed up your blog creation with <a href="https://differ.blog/differ-ai"><strong><em>DifferAI</em></strong></a>.</blockquote><blockquote>Available for <strong><em>free</em> </strong>exclusively on the <strong><em>free and open blogging platform, </em></strong><a href="https://differ.blog/"><strong><em>Differ</em></strong></a><strong><em>.</em></strong></blockquote><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h3>Call Method</h3><p>Using call(), we can borrow the printName() function for our myName object as shown below:</p><pre>printName.call(myName, &quot;Palia&quot;, &quot;India&quot;);</pre><p>The first argument is the context or owner object (i.e. myName in our case). The rest of the values (“Palia” and “India”) are extra arguments that the printName() function accepts.</p><p><strong><em>Output:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*MGkmAE06sNjmjvvGSbEO8A.png" /></figure><h4>Polyfill for call():</h4><p>Every function in JavaScript has access to these call(), apply() and bind() methods. So similarly, every function in JavaScript should have access to our myCall method. It can be done by putting the myCall function inside the Function prototype.</p><pre>eg. Function.prototype.myCall = function(){}</pre><p>Simple Polyfill for call():</p><pre>Function.prototype.myCall = function(context, ...args){<br>    context.myFn = this;<br>    context.myFn(...args);<br>}</pre><pre>printName.myCall(myName, &quot;Palia&quot;, &quot;India&quot;);</pre><p>The above code is a simple polyfill for the call() method. Here <strong>context</strong> points to the <strong>myName</strong> object and the <strong>this</strong> keyword points to the <strong>printName()</strong> function. The parameter <strong>…arg</strong>s in the function definition represents all the extra parameters (e.g. city and country) that we can pass while using our <strong>myCall</strong> method.</p><p>All we are doing here is assigning the <strong>printName()</strong> function as a property (<strong>myFn</strong>) to the <strong>myName</strong> object and executing it. But it’s not a complete solution. What if the property <strong>myFn</strong> already exists inside <strong>myName</strong>? We’ll be overwriting it. So we need to make sure that the name of the property we are using is unique.</p><p>Full polyfill:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2209f6c3849677bdd98ca86f47383487/href">https://medium.com/media/2209f6c3849677bdd98ca86f47383487/href</a></iframe><p>In the above code, we are generating a random property using Math.random() (to make sure the property is unique).</p><h3>Apply Method</h3><p>The only difference between the call() and apply() methods is that the call() method takes arguments separately but the apply() method takes arguments as an array. See the below example.</p><pre>printName.apply(myName, [&quot;Palia&quot;, &quot;India&quot;]);</pre><h4>Polyfill for apply():</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/138a9c82b7ba18a81c1b64a318c4bbc6/href">https://medium.com/media/138a9c82b7ba18a81c1b64a318c4bbc6/href</a></iframe><p>As you can see, the polyfill for apply() is almost the same as the polyfill for call(). The only difference is we don’t have <strong>…args</strong> as a parameter in the function definition. We have just one single args parameter because it’s a single array/list.</p><h3>Bind Method</h3><p>Instead of invoking the printName() method directly, the bind() method returns us a function which we can invoke later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*8P-RfYyvJCewfGYotEaK2Q.gif" /></figure><p>The context and the arguments are preserved. The beauty of the bind() function is that you can even pass some/more arguments to the returned function (i.e. result() in our case).</p><pre>const result = printName.bind(myName, &quot;Palia&quot;);<br>result(&quot;India&quot;);</pre><h4>Polyfill for bind():</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12fc123a1c2af39e2d4d81d7d76b518f/href">https://medium.com/media/12fc123a1c2af39e2d4d81d7d76b518f/href</a></iframe><p>Here, the <strong>this </strong>keyword points to the <strong>printName()</strong> function. The variable <strong>args[0] </strong>is the first argument passed to our myBind() method (i.e. the myName object) and <strong>ctx</strong> contains all the other arguments passed to our myBind() method. Parameter <strong>…a</strong> contains all the arguments that can be passed to the result2() method. And at last, we used the <strong>call()</strong> method to invoke the <strong>printName()</strong> function with the <strong>myName</strong> object as context and all the arguments combined.</p><h3>Video Explanation:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgeWKu-iXsww&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgeWKu-iXsww&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb69eed581fd3397474a423e90d74d58/href">https://medium.com/media/cb69eed581fd3397474a423e90d74d58/href</a></iframe><h3>Learn more:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FixLo_7qggm0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DixLo_7qggm0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FixLo_7qggm0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f90fd7f59d9f131401a452609a80dc8/href">https://medium.com/media/4f90fd7f59d9f131401a452609a80dc8/href</a></iframe><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b4ba313273" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/writing-polyfills-for-call-apply-and-bind-methods-in-javascript-13b4ba313273">How to write polyfills for the call(), apply(), and bind() methods in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DangerouslySetInnerHTML in React JS Explained]]></title>
            <link>https://javascript.plainenglish.io/dangerouslysetinnerhtml-in-react-js-explained-4dfc3b80be82?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dfc3b80be82</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Sat, 05 Mar 2022 05:14:19 GMT</pubDate>
            <atom:updated>2022-03-05T10:55:48.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_YRBNWSokQyFnITNtJiYg.png" /></figure><p><strong>dangerouslySetInnerHTML</strong> is an attribute under DOM elements in React.<br>According to the <a href="https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml">official documentation</a>, dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM to set HTML programmatically or from an external source.</p><h3>Syntax and Need to use dangerouslySetInnerHTML</h3><p>In simple vanilla JS to insert the HTML into the web page we use innerHTML property like given below.</p><pre>&lt;div innerHTML=&lt;p&gt;A sample paragraph&lt;/p&gt;&lt;/div&gt;</pre><pre>or</pre><pre>document.querySelector(&quot;.testClass&quot;)= &#39;&lt;p&gt;A sample paragraph&lt;/p&gt;&#39;;</pre><p>But if we try to do the same in React. We will get an error as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*-mlSCRamu7N6Q6pHcACevA.png" /></figure><p>The syntax to use dangerouslySetInnerHTML is pretty easy. Instead of innerHTML you have to type out dangerouslySetInnerHTML and pass an object with a __html key. For example:</p><pre>&lt;div dangerouslySetInnerHTML={{__html: &#39;&lt;p&gt;lorem ipsum&lt;/p&gt;&#39;}}&gt;&lt;/div&gt;</pre><p>But why is it called <strong><em>dangerouslySetInnerHTML? </em></strong>That’s because<strong><em> </em></strong>this property is <strong>dangerous</strong>, and using it carelessly can create XSS vulnerabilities in your application. Let’s understand briefly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*k59fb9I0L99NxuYo46Ezpw.gif" /></figure><h3>Why is it called dangerouslySetInnerHTML?</h3><p>The name <strong><em>dangerouslySetInnerHTML</em></strong> is intentionally chosen to be frightening. It’s not a naming mistake.</p><p>In general, setting HTML from code is risky because it may expose your users to a <a href="https://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting (XSS)</a> attack. You can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.</p><p>If you’re allowing users to insert HTML directly into your web page, they can technically embed scripts and malicious code and when you display that HTML in your react app those scripts may execute. An example is shown below.</p><pre>import React from &quot;react&quot;;<br>import &#39;./App.css&#39;;</pre><pre>const App = () =&gt; {</pre><pre>const data = `<br>  &lt;h3&gt;Welcome to this page&lt;/h3&gt;<br>  &lt;p&gt;May the code be with you&lt;/p&gt;<br>  &lt;img src=??? onerror=&quot;alert(&#39;XSS&#39;)&quot; /&gt;<br>  `;</pre><pre>return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h2&gt;Understanding dangerouslySetInnerHTML&lt;/h2&gt;<br>      &lt;div<br>        style={{ padding: &quot;10px&quot;, fontSize: &#39;17px&#39;, textAlign: &#39;center&#39; }}<br>        dangerouslySetInnerHTML={{ __html: data }}<br>      &gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNoSkhmebLAWWYiR0pYkaQ.png" /></figure><p>That’s why you need to make sure your HTML is sanitized before you insert it in your react app. You can use libraries like <a href="https://www.npmjs.com/package/dompurify">dompurify</a> to do so.</p><p>An example of how you can sanitize your code using dompurify is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/084b081fe55420b1c96c63a9cc082080/href">https://medium.com/media/084b081fe55420b1c96c63a9cc082080/href</a></iframe><h3>Performance</h3><p>When you are using dangerouslySetInnerHTML, behind the scenes it let’s React know that the HTML inside of that component is not something it cares about as it is coming from another source.</p><p>Because React uses a virtual DOM, when it goes to compare the difference against the real DOM, it can simply skips the comparison against the virtual DOM to gain some extra performance.</p><p>If you simply use innerHTML, React has no way to know the DOM node has been modified.</p><h3>Conclusion</h3><p>In conclusion, dangerouslySetInnerHTML is nothing but a replacement of innerHTML in React and should be used with care. The name <strong><em>dangerouslySetInnerHTML</em></strong> is intentionally chosen to remind you that it’s dangerous and may cause XSS vulnerabilities so that you make sure your HTML is sanitized before you insert it in your react app.</p><h3>Video Explanation:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNPWVE3pC06M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNPWVE3pC06M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNPWVE3pC06M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e2fd32c096e9d52802a8e7c0da558a7/href">https://medium.com/media/8e2fd32c096e9d52802a8e7c0da558a7/href</a></iframe><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dfc3b80be82" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/dangerouslysetinnerhtml-in-react-js-explained-4dfc3b80be82">DangerouslySetInnerHTML in React JS Explained</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MutationObserver in JavaScript Explained]]></title>
            <link>https://javascript.plainenglish.io/mutation-observer-in-javascript-21a85a4ceb24?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/21a85a4ceb24</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 03:30:55 GMT</pubDate>
            <atom:updated>2022-01-27T09:32:16.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is MutationObserver?</h3><p>MutationObserver is a Web API provided by modern browsers for detecting changes in the DOM. Using MutationObserver, when something in the DOM changes, we can invoke a callback function to react to those changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UL72khflMdsAeGEfc-xdjQ.gif" /></figure><p>Why would we even need to do that?</p><p>There are quite a few cases in which MutationObserver API can come really handy. For instance, we want to notify the user that some change has occurred on the web page he’s currently on. Another use-case can be if we are using a library that we don’t have control over.</p><h3>Polling</h3><p>The MutationObserver, however, has not always been around. So what did developers use before the MutationObserver? The simplest and most common way was polling. Polling is a technique in which we look for new data again and again over a given interval.</p><p>Using polling with browser setInterval WebAPI we can set up a task that would periodically check if any changes occurred in the DOM. Below is a very simple example of polling in JS.</p><pre>const poller = setInterval(function () {<br>  const node = document.querySelector(&#39;.any-dom-element&#39;)<br>  if (node) {<br>    console.log(node)<br>    clearInterval(poller)<br>  }<br>}, 1000)</pre><p>In the above code, the setInterval function will keep running every second until the node is available in the DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*tAeFWJPxRNrBGMx5SG1F2w.gif" /></figure><p>The problem with this approach was that it significantly degraded web app/website performance.</p><h3>How to use MutationObserver</h3><p>Implementing MutationObserver into your app is very easy. First, we need to create a MutationObserver instance by passing it a function that would be called every time a mutation has occurred. The first argument (i.e “mutations”) of the function is a collection of all mutations which have occurred in a single batch. Each mutation provides information about its type and the changes which have occurred.</p><pre>var mutationObserver = new MutationObserver(function(mutations) {<br>    mutations.forEach(function(mutation) {<br>        console.log(mutation);<br>    });<br>});</pre><p>The second thing we need to do is to use observe() method to start observing the DOM changes. The targetNode is the root of the subtree of nodes to monitor for changes. The observerOptions parameter contains properties we want to observe eg. childList, attributes..etc.</p><pre>mutationObserver.observe(targetNode, observerOptions);</pre><p>We can use the disconnect() method anytime to stop observing for the specified DOM changes.</p><pre>mutationObserver.disconnect();</pre><h3>Example:</h3><p>Let’s say we are using a library that will randomly insert or remove an anime name into the dom. And we wanna now what exact anime name is it adding/removing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/129257e9f6cdb721d72c486f51ffc073/href">https://medium.com/media/129257e9f6cdb721d72c486f51ffc073/href</a></iframe><p>Now if we normally try to access this added anime name, we will get null as the output.</p><pre>import &#39;./animes.js&#39;<br>console.log(document.querySelector(&#39;ul.animes li&#39;)); //output-&gt; null</pre><p>That’s because our library may take up to 2 seconds to add this anime name in the DOM. Here we can create a MutationObserver to notify us whenever an anime name is added or removed in the DOM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e918b643cdddbb58a6c2e31a3ec3095/href">https://medium.com/media/7e918b643cdddbb58a6c2e31a3ec3095/href</a></iframe><p>Here we are providing { childList: true} as observerOptions to monitor for the child node changes only. The output will be as shown in the below GIF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqeMyAA7r0wic3iYwiGomg.gif" /></figure><h4>Video Explanation:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F36ZoabEbu1o&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D36ZoabEbu1o&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/44f8002bab3add5089228d3676dbbc62/href">https://medium.com/media/44f8002bab3add5089228d3676dbbc62/href</a></iframe><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21a85a4ceb24" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mutation-observer-in-javascript-21a85a4ceb24">MutationObserver in JavaScript Explained</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Started with React Testing Library and Jest]]></title>
            <link>https://javascript.plainenglish.io/getting-started-with-react-testing-library-and-jest-ccdc4d333b10?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccdc4d333b10</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 18:47:18 GMT</pubDate>
            <atom:updated>2022-01-03T05:34:59.161Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to Jest and React Testing Library for beginners.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kldCKUiVz-wzg-DE" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>React testing library has become the most popular option to write test cases for React applications. These test cases resemble how a user would use your application. If you are using the latest version of the create-react-app tool then you already have Jest and Testing Library already installed for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*KsZa2WAcA16gHxlNuezzBQ.gif" /></figure><p>Before diving into the code, let’s get a quick recap of the basics of Jest.</p><pre>const expected = true;<br>const actual = false;<br>describe(&quot;simple jest test&quot;, () =&gt; {<br>  test(&quot;it works&quot;, () =&gt; {<br>    expect(actual).toBe(expected);<br>  });<br>});</pre><p>The above code is an example of a simple Jest test. It contains the following:</p><ol><li>describe breaks our test suite into components.</li></ol><p>2. test function is a test case.</p><p>3. expect function is used every time you want to test a value.</p><p>Now let’s look into the react code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Yd0d9zHOD2lKLnpDgDr5_Q.gif" /></figure><p>Full Source code: <a href="https://github.com/ankitsaxena21/React-ts-RTL">Github Repo Link</a>.</p><p>Below is a simple todo app built with react and typescript. All it does is that it takes some text as an input and on pressing enter, it adds the entered text to the list. Next, we will be writing test cases for this application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe3fdf2e65bf23c70a1e64c0b96f0218/href">https://medium.com/media/fe3fdf2e65bf23c70a1e64c0b96f0218/href</a></iframe><h4><strong>1. Basic Test</strong></h4><p>First, let’s test the basic rendering functionality of our react app. For example, if the component or element is properly rendering on the screen or not.</p><pre>import Todo from &#39;./Todo&#39;;</pre><pre>it(&#39;Renders without crashing&#39;, () =&gt; {<br>   render(&lt;Todo /&gt;);<br>   const linkElement = screen.getByText(/Todo App/i);<br>   expect(linkElement).toBeInTheDocument();<br>});</pre><p>Here we are importing our &lt;Todo /&gt; component and virtually renders it using the render() function. We will be using queries to get the DOM element we want. Queries are used to find elements on the page (<a href="https://testing-library.com/docs/queries/about#types-of-queries">more about Queries from RTL documentation</a>).</p><p>We are using the getByText() query provided by RTL. It will give us all the elements that have a text node with textContent matching the given TextMatch (i.e — “Todo App”).</p><p>Jest provides the .toBeInTheDocument() matcher, which can be used to assert that an element is in the body of the document, or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Msjo9Dzr6AntMsTBVVrvRw.gif" /></figure><p><strong>Tip</strong>: we can use screen.debug() to see the current HTML output of components.</p><h4><strong>2. Testing Events</strong></h4><p>Now we will check how to test for events. e.g., onChange, onClick, etc.</p><pre>it(&quot;When the Enter button is pressed, it creates a new todo item&quot;, () =&gt; {<br>    const { getByTestId, getByText } = render(&lt;Todo /&gt;);<br>    const event = { target: { value: &quot;test val&quot; } };<br>    fireEvent.change(getByTestId(&quot;todo-input&quot;), event);<br>    expect(getByTestId(&quot;todo-input&quot;)).toHaveValue(&quot;test val&quot;);<br>    fireEvent.submit(getByTestId(&quot;add&quot;));<br>    expect(getByText(&quot;test val&quot;)).toBeInTheDocument();<br>  });</pre><p>In the above code, first, we are getting the input by getByTestId(). It’s another way to get an element from the DOM tree having a particular data-testid attribute.(<a href="https://testing-library.com/docs/queries/bytestid/">More about getByTestId from RTL documentation</a>).</p><p>We are using the fireEvent property provided by RTL to test for events. The second argument (i.e eventProperties) passed to fireEvent is the property that will be assigned to the node which is receiving the event. In other words, the value the element should have when triggering the event. (<a href="https://testing-library.com/docs/dom-testing-library/api-events/#fireevent">More about fireEvent from RTL documentation</a>).</p><pre>const { getByTestId, getByText } = render(&lt;Todo /&gt;);<br> const event = { target: { value: &quot;test val&quot; } };<br> fireEvent.change(getByTestId(&quot;todo-input&quot;), event);</pre><p>Once the event is fired then we check the DOM to see whether the input has the same value that we passed to fireEvent (in the second argument).</p><pre>expect(getByTestId(&quot;todo-input&quot;)).toHaveValue(&quot;test val&quot;);</pre><p>Then, we did the same thing for the form submit event and then check whether the entered value in the input box is rendered in the list or not.</p><pre>fireEvent.submit(getByTestId(&quot;add&quot;));<br>expect(getByText(&quot;test val&quot;)).toBeInTheDocument();</pre><p><strong>Note</strong>: Another way to test events using RTL is through user-event. (<a href="https://testing-library.com/docs/ecosystem-user-event/">More about user-event from RTL documentation</a>)</p><h4><strong>3. Bonus: Testing API’s</strong></h4><p>Another important part of any react application is the APIs we are using. To test the working of these APIs, we’ll mock service workers. It is a simple and efficient way of mocking axios and fetch in testing.</p><p>What we have below is a simple JavaScript function that will make an API call (<a href="https://animechan.vercel.app/guide">Animechan API Link</a>) using axios and return us a random anime name.</p><pre>import axios from &#39;axios&#39;;</pre><pre>const fetchData = () =&gt; {<br>    return axios.get(&#39;<a href="https://animechan.vercel.app/api/random&#39;">https://animechan.vercel.app/api/random&#39;</a>)<br>        .then(res =&gt; {<br>            return res.data.anime<br>        })<br>        .catch(err =&gt; {<br>            console.log(err)<br>        })<br>};</pre><pre>export default fetchData;11</pre><p>Here we don’t wanna make actual API requests mainly for the following reasons:</p><ol><li>It’s slow</li><li>It’s unpredictable (the response returned from the API may be different for each request)</li></ol><p>So what we actually do is we create a mock server as shown in the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ce36859b597b0d594bb0742ce9614ce/href">https://medium.com/media/9ce36859b597b0d594bb0742ce9614ce/href</a></iframe><p>The first few things to import to this test file are {rest} from ‘msw’ and {setupServer} from ‘msw/node’. We then create a server variable and set it equal to the setupServer function. Essentially what setupServer is doing is:</p><ol><li>Setting up a server i.e listens for any requests made to the provided API.</li><li><strong>Intercepts</strong> them, and</li><li>Handles what should be the response.</li></ol><p>Here beforeAll() and afterAll() are used to run some particular code (in this case start and close the server) before and after each test run.</p><p>Now we can simply use “await fetchData()” to call our API and use expect() to check if the server returns the expected value or not. The real API server may return any random anime name. However, our Mock Service Worker intercepts the request and returns ‘naruto’ in the response, therefore our test will pass!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKkSXZgXCrGBI9ihB3RMQg.gif" /></figure><p>Full Source code: <a href="https://github.com/ankitsaxena21/React-ts-RTL">Github Repo Link</a>.</p><p>Video Explanation:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_SybsO4URZ0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_SybsO4URZ0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_SybsO4URZ0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/29b0358798d984dfdcf95a922344c2ab/href">https://medium.com/media/29b0358798d984dfdcf95a922344c2ab/href</a></iframe><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter</em></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><em>community Discord</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccdc4d333b10" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/getting-started-with-react-testing-library-and-jest-ccdc4d333b10">Get Started with React Testing Library and Jest</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Skeleton Loading Animation With CSS]]></title>
            <link>https://javascript.plainenglish.io/adding-skeleton-loading-animation-with-css-e6833f6e1d0a?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6833f6e1d0a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Sat, 25 Sep 2021 13:36:01 GMT</pubDate>
            <atom:updated>2021-09-26T11:08:23.508Z</atom:updated>
            <content:encoded><![CDATA[<p>The term <strong>Skeleton Loading Animation </strong>may seems new but it is something that you have seen on almost every popular platform (eg. Facebook, Youtube, LinkedIn etc).</p><p>When the site content is taking time to load due to slower Network, we used to see a loading icon/gif which indicates that the content is being loaded.<br>The older way to indicate that the content is still loading:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*pyRw1qikTI1eqGm9.gif" /></figure><p>The above loading icon will let the user know that the content is being loaded. But, it is not a Great User Experience.</p><p>How can we make it better?</p><p><strong>Introducing the skeleton loading screens:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*gLEa0jOJRKBh5BZU7KVaiQ.gif" /></figure><p>Skeleton loading animations<strong> </strong>are animated placeholders for the information that is still loading. It mimic the structure and look of the entire view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXQHAaNrf_1leRuzFZHaBQ.gif" /></figure><p>This is the <strong>“Skeleton Loading Screen!”. </strong>It represents the structure of the ui that is going to be loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ULMQxUEWT9oi1ktOHkGFVg.gif" /></figure><h3>Let’s Learn How to implement this in our app</h3><p>Full source code: <a href="https://github.com/ankitsaxena21/Skeleton-Loading-Animation-With-CSS">Github Repo</a></p><p>Below is a simple code that fetches data from <a href="https://fakestoreapi.com/">fake store api</a> and populate the data on the DOM.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;Document&lt;/title&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div class=&quot;grid&quot;&gt;&lt;/div&gt;<br>  <br>  &lt;template id=&quot;card-template&quot;&gt;<br>    &lt;div class=&quot;card&quot;&gt;<br>      &lt;div class=&quot;header&quot;&gt;<br>        &lt;img class=&quot;header-img&quot; data-img /&gt;<br>        &lt;div class=&quot;title&quot; data-title&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div data-body&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/template&gt;<br>&lt;/body&gt;<br>&lt;script&gt;<br>  const grid = document.querySelector(&#39;.grid&#39;)<br>  const cardTemplate = document.getElementById(&#39;card-template&#39;)</pre><pre>fetch(&quot;<a href="https://fakestoreapi.com/products/category/electronics">https://fakestoreapi.com/products/category/electronics</a>&quot;)<br>    .then(res =&gt; res.json())<br>    .then(posts =&gt; {<br>      grid.innerHTML = &#39;&#39;<br>      posts.forEach(post =&gt; {<br>        const div = cardTemplate.content.cloneNode(true)<br>        div.querySelector(&#39;[data-img]&#39;).src = post.image<br>        div.querySelector(&#39;[data-title]&#39;).textContent=&quot;$&quot;+post.price<br>        div.querySelector(&#39;[data-body]&#39;).textContent = post.title<br>        grid.append(div)<br>      })<br>  })<br>&lt;/script&gt;<br>&lt;/html&gt;</pre><p>Right now the loading of our app looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*4UEtclCme4cMYKLhnGt1Fg.gif" /></figure><p>Now let’s add the skeleton loading animation to it.</p><p>Replace the content in the body tag with the code given below. We are adding few divs and classes to our previous code.</p><pre>&lt;div class=&quot;grid&quot;&gt;&lt;/div&gt;<br>  <br>  &lt;template id=&quot;card-template&quot;&gt;<br>    &lt;div class=&quot;card&quot;&gt;<br>      &lt;div class=&quot;header&quot;&gt;<br>        &lt;img class=&quot;header-img skeleton&quot; data-img                                                                                            src=&quot;<a href="https://source.unsplash.com/100x100/?nature">https://source.unsplash.com/100x100/?e</a>lectronics&quot; /&gt;<br>        &lt;div class=&quot;title&quot; data-title&gt;<br>          &lt;div class=&quot;skeleton skeleton-text&quot;&gt;&lt;/div&gt;<br>          &lt;div class=&quot;skeleton skeleton-text&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div data-body&gt;<br>        &lt;div class=&quot;skeleton skeleton-text&quot;&gt;&lt;/div&gt;<br>        &lt;div class=&quot;skeleton skeleton-text&quot;&gt;&lt;/div&gt;<br>        &lt;div class=&quot;skeleton skeleton-text&quot;&gt;&lt;/div&gt;<br>        &lt;div class=&quot;skeleton skeleton-text&quot;&gt;&lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/template&gt;</pre><p>The .skeleton and .skeleton-text classes are for showing placeholder elements for the content to be loaded.</p><p>Now let’s add the required CSS.</p><pre>.skeleton {<br>  opacity: .7;<br>  animation: skeleton-loading 1s linear infinite alternate;<br>}</pre><pre>.skeleton-text {<br>  width: 100%;<br>  height: .5rem;<br>  margin-bottom: .25rem;<br>  border-radius: .125rem;<br>}</pre><pre>.skeleton-text:last-child {<br>  margin-bottom: 0;<br>  width: 80%;<br>}</pre><pre><a href="http://twitter.com/keyframes">@keyframes</a> skeleton-loading {<br>  0% {<br>    background-color: hsl(200, 20%, 70%);<br>  }</pre><pre>100% {<br>    background-color: hsl(200, 20%, 95%);<br>  }<br>}</pre><p>.skeleton class has a custom animation by name &#39;skeleton-loading&#39; for changing the background colour, duration 1 seconds, count of infinite (keeps repeating) in alternate cycles.</p><p>Now to show a number of placeholder skeleton cards &amp; texts and replace them with the actual fetched content, add a for loop before making the fetch request (as shown below) . It’ll clone all the data from our template and put it inside the grid.</p><pre>//inside the script tag<br>const grid = document.querySelector(&#39;.grid&#39;)<br>const cardTemplate = document.getElementById(&#39;card-template&#39;)<br>for (let i = 0; i &lt; 6; i++) {<br>  grid.append(cardTemplate.content.cloneNode(true))<br>}</pre><pre>fetch(&quot;<a href="https://fakestoreapi.com/products/category/electronics">https://fakestoreapi.com/products/category/electronics</a>&quot;)<br>    .then(res =&gt; res.json())<br>    .then(posts =&gt; {<br>      grid.innerHTML = &#39;&#39;<br>      posts.forEach(post =&gt; {<br>        const div = cardTemplate.content.cloneNode(true)<br>        div.querySelector(&#39;[data-img]&#39;).src = post.image<br>        div.querySelector(&#39;[data-title]&#39;).textContent = &quot;$&quot; + post.price<br>        div.querySelector(&#39;[data-body]&#39;).textContent = post.title<br>        grid.append(div)<br>      })<br>  })</pre><p>Now with these changes we have successfully added skeleton loading animation to our app. (select slow 3G in network tab of chrome dev tools to see how the page loads in case of slower network)</p><p><strong>The Final Result :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*bVxhtq2XQ7nw2vNb4AhiYg.gif" /></figure><p>Source code: <a href="https://github.com/ankitsaxena21/Skeleton-Loading-Animation-With-CSS">Github Repo</a></p><p>So this is how you can implement skeleton loading animation with CSS. I hope some of you will find this as useful as it’s been for me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6833f6e1d0a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/adding-skeleton-loading-animation-with-css-e6833f6e1d0a">Adding Skeleton Loading Animation With CSS</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Skeleton Loading Screens in React]]></title>
            <link>https://javascript.plainenglish.io/implementing-skeleton-ui-in-react-js-7eeb409584de?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eeb409584de</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Fri, 24 Sep 2021 08:53:32 GMT</pubDate>
            <atom:updated>2021-09-27T08:09:45.247Z</atom:updated>
            <content:encoded><![CDATA[<p>The term <strong>Skeleton Loading Screens </strong>may seem new but it is something that you have seen on almost every popular platform (eg. Facebook, YouTube, LinkedIn, etc). These are animated placeholders for the information that is still loading. It mimics the structure and look of the entire view.</p><p>When the site content is taking time to load due to a slower network, we are used to seeing a loading icon/gif which indicates that the content is being loaded.</p><p>The older way to indicate that the content is still loading:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*1x2My3Jk-xykpOyahxhJ0Q.gif" /></figure><p>The above loading icon will let the user know that the content is being loaded. But, in my opinion, it is not a great user experience.</p><p>How can we make it better?</p><p><strong>Introducing skeleton loading screens:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoDyVUqmC1O230RbD1rGoQ.png" /></figure><p>The above image is the skeleton loading screen from YouTube.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*33PkguILLO7GBsdbGlSx3w.gif" /></figure><p>It mimics the structure of the UI that is going to be loaded.</p><p>We’ll learn two ways to implement this in any React project.</p><p>Source Code: <a href="https://github.com/ankitsaxena21/React-Skeleton-Loading-UI">Github Souce Code</a></p><p>Below we have a simple App.js file with two routes. One for our custom implemented code and the other using react-loading-skeleton.</p><pre>import &#39;./App.css&#39;;<br>import { Route, Switch } from &#39;react-router-dom&#39;;<br>import ProductsCustom from &#39;./components/ProductsCustom&#39;;<br>import ProductsLib from &#39;./components/ProductsLib&#39;;<br>import Navbar from &#39;./components/Navbar&#39;;<br>function App() {<br>  return (<br>    &lt;main&gt;<br>      &lt;Navbar /&gt;<br>      &lt;Switch&gt;<br>        &lt;Route path=&quot;/&quot; component={ProductsCustom} exact /&gt;<br>        &lt;Route path=&quot;/lib&quot; component={ProductsLib} /&gt;<br>      &lt;/Switch&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><pre>export default App;</pre><h3>1. Implementing by writing our own custom code</h3><p>Let’s build the custom one first. Create a folder named components and inside that folder create a file with the name ProductsCustom.js.</p><pre>import { useState, useEffect } from &quot;react&quot;;</pre><pre>import SkeletonProduct from &quot;../skeleton/SkeletonProduct&quot;;</pre><pre>const ProductsCustom = () =&gt; {</pre><pre>    const [products, setProducts] = useState([]);</pre><pre>    const [loader, setLoader] = useState(false);</pre><pre>    useEffect(() =&gt; {</pre><pre>    setLoader(true);</pre><pre>    setTimeout(async () =&gt; {</pre><pre>     const response = await fetch(&#39;https://fakestoreapi.com/products/category/electronics&#39;);</pre><pre>     const data = await response.json();</pre><pre>     setLoader(false);</pre><pre>     setProducts(data);</pre><pre>     }, 4000);</pre><pre>  }, []);<br></pre><pre>return (</pre><pre>&lt;div className=&quot;container&quot;&gt;</pre><pre>  &lt;div className=&quot;row&quot;&gt;</pre><pre>    {!loader ?</pre><pre>    products.map(product =&gt; (</pre><pre>     &lt;div className=&quot;col-3&quot; key={product.id}&gt;</pre><pre>      &lt;div className=&quot;product&quot;&gt;</pre><pre>       &lt;div className=&quot;product-image&quot;&gt;</pre><pre>        &lt;img src={product.image} alt=&quot;&quot; /&gt;</pre><pre>       &lt;/div&gt;</pre><pre>     &lt;div className=&quot;product-body&quot;&gt;</pre><pre>      &lt;div className=&quot;product-title&quot;&gt;{product.title.slice(0, 30)}.             </pre><pre>      &lt;/div&gt;</pre><pre>     &lt;div className=&quot;product-price&quot;&gt;$ {product.price}&lt;/div&gt;</pre><pre>     &lt;div className=&quot;product-button&quot;&gt;&lt;a href=&quot;www.youtube.com&quot;&gt;buy n now&lt;/a&gt;&lt;/div&gt;</pre><pre>     &lt;/div&gt;</pre><pre>    &lt;/div&gt;</pre><pre>    &lt;/div&gt;</pre><pre>   )) : [1, 2, 3, 4, 5, 6].map(loading =&gt; (</pre><pre>   &lt;div className=&quot;col-3&quot; key={loading}&gt;</pre><pre>    &lt;SkeletonProduct /&gt;</pre><pre>   &lt;/div&gt;</pre><pre>  ))}</pre><pre>  &lt;/div&gt;</pre><pre> &lt;/div&gt;</pre><pre> )</pre><pre>}</pre><pre>export default ProductsCustom;</pre><p>Here we are fetching data from <a href="https://fakestoreapi.com/">fake store api</a> and creating a delay of 4 seconds using setTimeout before populating the data on the screen. Until the page loads completely, we are showing just a simple message-“loading“.(shown below in the gif)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywb_-eB80RWZdoDvsprXGQ.gif" /></figure><p>Now we have to replace this “loading” text with some skeleton UI. For that let’s create a folder named skeleton and inside that folder create a file SkeletonProduct.js.</p><pre>import Skeleton from &quot;./Skeleton&quot;</pre><pre>import &#39;./skeleton.css&#39;;</pre><pre>const SkeletonProduct = () =&gt; {</pre><pre>  return (</pre><pre>   &lt;div className=&quot;skeleton-wrapper&quot;&gt;</pre><pre>    &lt;Skeleton type=&quot;thumbnail&quot; /&gt;</pre><pre>    &lt;Skeleton type=&quot;text-lg&quot; /&gt;</pre><pre>    &lt;Skeleton type=&quot;text-md&quot; /&gt;</pre><pre>    &lt;Skeleton type=&quot;text-sm&quot; /&gt;</pre><pre>    &lt;div className=&quot;shimmer-wrapper&quot;&gt;</pre><pre>    &lt;div className=&quot;shimmer&quot;&gt;&lt;/div&gt;</pre><pre>    &lt;/div&gt;</pre><pre>   &lt;/div&gt;</pre><pre>  )</pre><pre>}</pre><pre>export default SkeletonProduct;</pre><p>Here &lt;Skeleton /&gt;is another component that we will create. It will take a type prop using which we can create skeleton UI for different kinds of elements using CSS. These classes-<strong>thumbnail</strong>, <strong>text-lg</strong>, <strong>text-md, </strong>and <strong>text-sm </strong>represent different sizes and kinds of UI elements.</p><pre>.skeleton {</pre><pre>   margin: 10px 0;</pre><pre>}</pre><pre>.skeleton-wrapper {</pre><pre>   width: 100%;</pre><pre>   position: relative;</pre><pre>}</pre><pre>.skeleton .thumbnail {</pre><pre>   width: 100%;</pre><pre>   min-height: 200px;</pre><pre>   background: #D2DBE2;</pre><pre>   border-radius: 7px;</pre><pre>}</pre><pre>.skeleton .text-lg {</pre><pre>   width: 100%;</pre><pre>   margin-top: 10px;</pre><pre>   background: #D2DBE2;</pre><pre>   border-radius: 7px;</pre><pre>   min-height: 10px;</pre><pre>}</pre><pre>.skeleton .text-md {</pre><pre>   width: 70%;</pre><pre>   margin-top: 10px;</pre><pre>   background: #D2DBE2;</pre><pre>   border-radius: 7px;</pre><pre>   min-height: 10px;</pre><pre>}</pre><pre>.skeleton .text-sm {</pre><pre>   width: 40%;</pre><pre>   margin-top: 10px;</pre><pre>   background: #D2DBE2;</pre><pre>   border-radius: 7px;</pre><pre>   min-height: 10px;</pre><pre>}</pre><p>The shimmer-wrapper class will be responsible for creating a shimmering effect on top of the &lt;SkeletonProduct /&gt; component. We are using a CSS animation to change the position of the shimmering div.</p><pre>.shimmer-wrapper {</pre><pre>   position: absolute;</pre><pre>   left: 0;</pre><pre>   top: 0;</pre><pre>   width: 100%;</pre><pre>   height: 100%;</pre><pre>   overflow: hidden;</pre><pre>}</pre><pre>.shimmer {</pre><pre>   width: 50%;</pre><pre>   height: 100%;</pre><pre>   opacity: 0.2;</pre><pre>   background: rgba(238, 238, 238, 0.966);</pre><pre>   transform: skewX(-20deg);</pre><pre>   animation: loader 1s linear infinite;</pre><pre>}</pre><pre>@keyframes loader {</pre><pre>  0% {</pre><pre>   transform: translateX(-150%);</pre><pre>  }</pre><pre>  50% {</pre><pre>   transform: translateX(-60%);</pre><pre>  }</pre><pre>  100% {</pre><pre>   transform: translateX(150%);</pre><pre>  }</pre><pre>}</pre><p>Let’s have a look at our Skeleton.js file. Below you can see we are using the ‘type’ prop for applying the respective class to the skeleton component.</p><pre>import &#39;./skeleton.css&#39;;</pre><pre>const Skeleton = ({type}) =&gt; {</pre><pre> return (</pre><pre>  &lt;div className=&quot;skeleton&quot;&gt;</pre><pre>   &lt;div className={type}&gt; &lt;/div&gt;</pre><pre>  &lt;/div&gt;</pre><pre>  )</pre><pre>}</pre><pre>export default Skeleton;</pre><p>Now instead of just displaying just “loading” text, we will show our &lt;SkeletonProduct /&gt; component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69a13e0f86be3e599135ddf0fb9b2ab9/href">https://medium.com/media/69a13e0f86be3e599135ddf0fb9b2ab9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*uTm2p-8-9GMLilvi6tIskQ.gif" /></figure><p>Now, our React app will load as shown in the above gif.</p><h3>2. Implement by using <a href="https://www.npmjs.com/package/react-loading-skeleton">react-skeleton-loading</a></h3><p>Another way is to use <a href="https://www.npmjs.com/package/react-loading-skeleton">react-skeleton-loading</a> npm package to implement the skeleton loading UI for our application.</p><p>Install the package using the command given below:</p><pre>npm i react-loading-skeleton</pre><p>Create another file inside the skeleton folder — SkeletonProductLib.js. we will import Skeleton and SkeletonTheme from react-loading-skeleton (&lt;Skeleton /&gt; is for adding the skeleton UI. &lt;SkeletonTheme /&gt; is to change the colors of all skeleton components).</p><pre>import React from &quot;react&quot;;</pre><pre>import Skeleton, { SkeletonTheme } from &quot;react-loading-skeleton&quot;;</pre><pre>const SkeletonProductLib = () =&gt; {</pre><pre>  return (<br>   <br>   &lt;SkeletonTheme&gt;</pre><pre>    &lt;section&gt;</pre><pre>    &lt;div style={{ padding: &quot;8px&quot; }}&gt;</pre><pre>    &lt;div&gt;</pre><pre>      &lt;Skeleton height={200} /&gt;</pre><pre>    &lt;/div&gt;</pre><pre>    &lt;div style={{ marginTop: &quot;7px&quot; }}&gt;</pre><pre>      &lt;Skeleton height={12} width={`100%`} /&gt;</pre><pre>    &lt;/div&gt;</pre><pre>    &lt;div style={{ marginTop: &quot;7px&quot; }}&gt;</pre><pre>      &lt;Skeleton height={12} width={`70%`} /&gt;</pre><pre>    &lt;/div&gt;</pre><pre>    &lt;div style={{ marginTop: &quot;7px&quot; }}&gt;</pre><pre>      &lt;Skeleton height={12} width={`40%`} /&gt;</pre><pre>    &lt;/div&gt;</pre><pre>    &lt;/div&gt;</pre><pre>   &lt;/section&gt;</pre><pre>  &lt;/SkeletonTheme&gt;</pre><pre>);</pre><pre>};</pre><pre>export default SkeletonProductLib;</pre><p>The &lt;Skeleton /&gt;component takes height and width as a prop to specify the height and width the placeholder UI will be taking.</p><p>Now instead of using our &lt;SkeletonProduct /&gt; component we will use this &lt;SkeletonProductLib /&gt; component that we just created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec819a6ed322d6028969fc281a6bdb6d/href">https://medium.com/media/ec819a6ed322d6028969fc281a6bdb6d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXQHAaNrf_1leRuzFZHaBQ.gif" /></figure><p>Our React app will load as shown in the above gif.</p><p>So this is how you can implement skeleton loading screens in React. I hope some of you will find this as useful as it’s been for me.</p><p>Project Source Code: <a href="https://github.com/ankitsaxena21/React-Skeleton-Loading-UI">Github Repo</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eeb409584de" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/implementing-skeleton-ui-in-react-js-7eeb409584de">How to Create Skeleton Loading Screens in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement Debouncing in React in 3 Different Ways]]></title>
            <link>https://javascript.plainenglish.io/implementing-debouncing-in-react-f3316ef344f5?source=rss-c5913db1e0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3316ef344f5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ankit Saxena]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 06:38:15 GMT</pubDate>
            <atom:updated>2024-08-02T06:22:29.857Z</atom:updated>
            <content:encoded><![CDATA[<p>Debouncing is used for optimizing the performance of a web app. It is done by limiting the rate of execution of a particular function (also known as rate limiting).</p><p>We will learn about debouncing by implementing it on an input box with an onChange event. When we’ll type something inside this input box, on every keystroke an API call will be made. If we go to the network tab on Chrome, and type results in the input box, we’ll see that on every letter we type, a network/API call is being made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Nv55lGOJ7lea_V5Y_kNBw.png" /></figure><p>This is not good from a performance point of view because if the user is typing, let’s say, 50 or 100 characters in the input box, then 50-100 API calls will be made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*jbeUxZIZcrdOtAziDiu0DQ.gif" /></figure><p>We will fix it with the help of debouncing.</p><blockquote><em>💡 </em>Speed up your blog creation with <a href="https://differ.blog/differ-ai"><strong><em>DifferAI</em></strong></a>.</blockquote><blockquote>Available for <strong><em>free</em> </strong>exclusively on the <strong><em>free and open blogging platform, </em></strong><a href="https://differ.blog/"><strong><em>Differ</em></strong></a><strong>.</strong></blockquote><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h3><strong>Method 1: Implementing from scratch</strong></h3><p>Let’s make a function debounce. It will return us another function (an optimized function). The logic behind this function will be that only when the time between two keypress events is greater than 500 milliseconds, only then will the data be fetched from the API. If the delay is more than 500 milliseconds, only then will the <em>handleChange</em> function be called.</p><p>We will use apply a function to fix our context. If the delay between these two keystroke events is less than 500 ms, then we should clear this setTimeout (timer variable). We will use this optimized function (returned from debounce function) instead of directly calling the handleChange method.</p><pre>const debounce = (func) =&gt; {<br>    let timer;<br>    return function (...args) {<br>      const context = this;<br>      if (timer) clearTimeout(timer);<br>      timer = setTimeout(() =&gt; {<br>        timer = null;<br>        func.apply(context, args);<br>      }, 500);<br>    };<br>  };</pre><pre>const handleChange = (value) =&gt; {<br>    fetch(`<a href="https://demo.dataverse.org/api/search?q=${value}`">https://demo.dataverse.org/api/search?q=${value}`</a>)<br>      .then((res) =&gt; res.json())<br>      .then((json) =&gt; setSuggestions(json.data.items));<br>  };</pre><p>Now we can go see in the network tab on Chrome, and type results. Only one or two times is the call made when we fully typed results inside the input box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7eYong3TOpQ0vfB60pKeQ.png" /></figure><p>Our debounce will be returning us a new function on every rendering. That we do not want so that we will use the <em>useCallBack</em> hook. It will provide us the memoized callback.</p><pre>const optimizedFn = useCallback(debounce(handleChange), []);</pre><p>Below is the full code for implementing debouncing from scratch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/685cf56a295c3f8ab4659872184b9d23/href">https://medium.com/media/685cf56a295c3f8ab4659872184b9d23/href</a></iframe><h3>Method 2: Using lodash</h3><p>Another way to implement debouncing is using <a href="https://www.npmjs.com/package/lodash">lodash</a>. Lodash provides a debounce method that we can use to limit the rate of execution of the handleChange function. Just wrap the callback function with the debounce method and provide the amount of delay we want between two events. Now if you go back on Chrome and check, it works the same.</p><pre>import { debounce } from &quot;lodash&quot;;</pre><pre>const handleChangeWithLib = debounce((value) =&gt; {<br>    fetch(`<a href="https://demo.dataverse.org/api/search?q=${value}`">https://demo.dataverse.org/api/search?q=${value}`</a>)<br>      .then((res) =&gt; res.json())<br>      .then((json) =&gt; setSuggestions(json.data.items));<br>  }, 500);</pre><h3>Method 3: Using react-debounce-input</h3><p>There is one more npm package called <a href="https://www.npmjs.com/package/react-debounce-input">react-debounce-input</a> that we can use. It is the simplest way compared to the previous two methods. Just use DebounceInput provided by the react-debounce-input library instead of using the normal input tag. And provide delay as an attribute. Now if we go back to Chrome and check again, calls are still made only when we fully type results.</p><pre>&lt;DebounceInput<br>     minLength={2}<br>     className=&quot;search&quot;<br>     placeholder=&quot;Enter something here...&quot;<br>     debounceTimeout={500}<br>     onChange={e =&gt; handleChange(e.target.value)} /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*1Tfzeh5N__cKiQU0IrksrA.gif" /></figure><p>So these are the 3 different methods of implementing debouncing in React. I hope some of you will find these as useful as they have been for me.</p><p>Check out this GitHub repository for the source code: s<a href="https://github.com/ankitsaxena21/react-debounce-tutorial">ource code link</a></p><p>Video explanation :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdtacfvLcoxY&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdtacfvLcoxY&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FdtacfvLcoxY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ce1e5ea4e421858d10548218851b297/href">https://medium.com/media/2ce1e5ea4e421858d10548218851b297/href</a></iframe><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3316ef344f5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/implementing-debouncing-in-react-f3316ef344f5">Implement Debouncing in React in 3 Different Ways</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>