<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: MokaDevLight</title>
    <description>The latest articles on DEV Community by MokaDevLight (@mokadevlight).</description>
    <link>https://dev.to/mokadevlight</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F806379%2Fe9ee8534-39c8-4abd-8dcb-68570e8cb52d.png</url>
      <title>DEV Community: MokaDevLight</title>
      <link>https://dev.to/mokadevlight</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mokadevlight"/>
    <language>en</language>
    <item>
      <title>Jest Testing</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Sat, 23 Apr 2022 10:49:02 +0000</pubDate>
      <link>https://dev.to/mokadevlight/jest-testing-2ckd</link>
      <guid>https://dev.to/mokadevlight/jest-testing-2ckd</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;When it comes to unit testing frameworks for JavaScript, Jest is certainly a serious contender for the #1 spot.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Initially, Jest was created by Facebook specifically for testing React applications. It’s one of the most popular ways of testing React components. Since its introduction, the tool has gained a lot of popularity. This popularity has led to the use of Jest for testing both JavaScript front-end and back-end applications.&lt;/p&gt;

&lt;p&gt;In this article, we’ll talk about the ins and outs of Jest to help you get started with testing. Before we get there, though, we’ll offer you a refresher on unit testing and its importance for software quality.&lt;/p&gt;

&lt;p&gt;After that, we’ll start covering Jest specifically, explaining:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;its definition&lt;/li&gt;
&lt;li&gt;what are its main advantages&lt;/li&gt;
&lt;li&gt;and some of its most important characteristics&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We’ll walk you through a 100% hands-on tutorial on how to get started with Jest. You’ll learn more about the vocabulary associated with Jest testing, like mocks and spies. Also, we’ll cover some of the basics of Jest testing, like using describe blocks and the keywords it and expect. Finally, we’ll take a look at snapshot testing and why it’s particularly useful for front-end testing. Let’s get started!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The What and Why of Unit Testing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The topic of software testing can often feel overwhelming. There are just too many types of testing, each operating on a different layer, verifying distinct aspects of the application and offering its unique type of feedback.&lt;/p&gt;

&lt;p&gt;Among the myriad types of automated testing, unit testing is often cited as the most important one—see: test automation pyramid. Unit tests verify the smallest parts of your application in complete isolation, ensuring they work as expected. In unit testing, you aren’t allowed to interact with external dependencies—e.g. make an HTTP call—nor generate any kind of side-effect.&lt;/p&gt;

&lt;p&gt;As a result of those properties, unit tests are usually:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;very fast to execute&lt;/li&gt;
&lt;li&gt;relatively easy to setup, not requiring any elaborate configuration&lt;/li&gt;
&lt;li&gt;very precise in the feedback they provide&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the scale of automated tests, unit tests sit at the extreme opposite of end-to-end testing.  The latter provide less-precise feedback, are generally slower, more fragile, though more realistic. The former are super precise in their feedback, are fast, and typically only fail due to the errors in the code.&lt;/p&gt;

&lt;p&gt;However, they are in less realistic, because in real life users don’t interact with units in complete isolation.&lt;/p&gt;

&lt;p&gt;To sum it up: unit tests are far from being the only type of tests your application needs, but they should represent a significant portion of your testing strategy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Is Jest?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Jest is a popular test framework for JavaScript. It claims to provide “delightful JavaScript testing” and, after our tutorial, I bet you might agree with this claim! Jest prides itself in offering a complete and hassle-free experience.&lt;/p&gt;

&lt;p&gt;The completeness comes from the fact that Jest doesn’t rely on third-party tools for much of its functionality, like some competitors do. And the hassle-free part is due to Jest’s zero configuration setup. You can install it and start writing your first test in no time.&lt;/p&gt;

&lt;p&gt;As mentioned in the introduction, Jest has gained a lot of popularity over recent years for both front-end and back-end testing. Many large companies—including Twitter, Instagram, Pinterest, and Airbnb—use Jest for React testing.&lt;/p&gt;

&lt;p&gt;Jest itself is actually not a library but a framework. There’s even a CLI tool that you can use from the command line. To give an example, the CLI tool allows you to run only specific tests that match a pattern. Besides that, it hosts much more functionality, which you can find in the CLI documentation.&lt;/p&gt;

&lt;p&gt;In summary, this means that Jest offers a test runner, assertion library, CLI tool, and great support for different mocking techniques. All of this makes it a framework and not just a library.&lt;/p&gt;

&lt;p&gt;Let’s take a quick look at the advantages of Jest.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages of Jest&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s a shortlist of Jest advantages.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Offers a CLI tool to control your tests easily&lt;/li&gt;
&lt;li&gt;Comes with an interactive mode that automatically runs all affected tests for the code changes you’ve made in your last commit&lt;/li&gt;
&lt;li&gt;Provides syntax to test a single test or skip tests with .only and .skip. This feature is useful when debugging individual tests&lt;/li&gt;
&lt;li&gt;Provides excellent documentation with plenty of examples and a supportive community. You can join the Jest community via Discord or ask questions on Stack Overflow&lt;/li&gt;
&lt;li&gt;Brings easy mocking to developers as it’s one of the most painful things to do for testing engineers. We explain further in this post how Jest mocking works&lt;/li&gt;
&lt;li&gt;Jest offers code coverage out of the box through its CLI—just use the –coverage option or the collectCoverage property in the Jest configuration file.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Jest Characteristics&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;From Jest’s website, we can find four main characteristics of Jest:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Zero config: “Jest aims to work out of the box, config free, on most JavaScript projects.” This means you can simply install Jest as a dependency for your project, and with no or minimal adjustments, you can start writing your first test.&lt;/li&gt;
&lt;li&gt;Isolated: Isolation is a very important property when running tests. It ensures that different tests don’t influence each other’s results. For Jest, tests are executed in parallel, each running in their own process. This means they can’t interfere with other tests, and Jest acts as the orchestrator that collects the results from all the test processes.&lt;/li&gt;
&lt;li&gt;Snapshots: Snapshots are a key feature for front-end testing because they allow you to verify the integrity of large objects. This means you don’t have to write large tests full of assertions to check if every property is present on an object and has the right type. You can simply create a snapshot and Jest will do the magic. Later, we’ll discuss in detail how snapshot testing works.&lt;/li&gt;
&lt;li&gt;Rich API: Jest is known for having a rich API offering a lot of specific assertion types for very specific needs. Besides that, its great documentation should help you get started quickly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before we dive a bit further into the Jest vocabulary, let’s show you how you can get started with this tool in practice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Get Started With Jest: A Practical, Hands-On Tutorial in 5 Steps&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We’ll now walk you through our five step tutorial on how to get started with testing using Jest.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Install Jest Globally&lt;/strong&gt;&lt;br&gt;
The first step will be to install Jest globally. That way, you gain access to Jest’s CLI. Make sure you have Node.js installed, because you’ll use npm.&lt;/p&gt;

&lt;p&gt;Go to your terminal and run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g jest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the installation is complete, execute jest –version to see the version installed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Create a Sample Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You’ll now create a npm-based project to house our production code and test code.&lt;/p&gt;

&lt;p&gt;Start by creating a folder and accessing it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir learning-jest
cd learning-jest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, run npm init -y to create a project. As a result, you should have a package.json file inside your folder, with this content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "learning-jest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, create a file called index.js and paste the following content on it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function fizz_buzz(numbers) {
    let result = []

    for (number of numbers) {
        if (number % 15 === 0) {
            result.push('fizzbuzz')
        } else if (number % 3 === 0) {
            result.push('fizz')
        } else if (number % 5 === 0) {
            result.push('buzz')
        } else {
            result.push(number)
        }
    }

    return result.join(', ')
}

module.exports = fizz_buzz;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above contains a function that solves the famous FizzBuzz programming interview question.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Add Jest to the Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You’ll now add Jest as a dev dependency to the project. Run the following command:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install --save-dev jest&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then, go to your package.json file and change this part:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;"scripts": {&lt;br&gt;
    "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"&lt;br&gt;
  },&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;To this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;"scripts": {&lt;br&gt;
    "test": "jest"&lt;br&gt;
  },&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Write Your First Test&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, create a new file called index.test.js. Paste the following content on it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fizz_buzz = require('./index');

describe("FizzBuzz", () =&amp;gt; {
    test('[3] should result in "fizz"', () =&amp;gt; {
      expect(fizz_buzz([3])).toBe('fizz');
    });

    test('[5] should result in "buzz"', () =&amp;gt; {
      expect(fizz_buzz([5])).toBe('buzz');
    });

    test('[15] should result in "fizzbuzz"', () =&amp;gt; {
      expect(fizz_buzz([15])).toBe('fizzbuzz');
    });

    test('[1,2,3] should result in "1, 2, fizz"', () =&amp;gt; {
      expect(fizz_buzz([3])).toBe('fizz');
    });

});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We’ll explain Jest’s syntax in more detail later. For now, understand we’re verifying that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;passing an array containing 3 should result in “fizz”&lt;/li&gt;
&lt;li&gt;an array containing 5 should result in “buzz”&lt;/li&gt;
&lt;li&gt;an array containing 15 should result in “fizzbuzz”&lt;/li&gt;
&lt;li&gt;passing an array with 1, 2, and 3 should result in “1, 2, fizz”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;5. Run Your First Test&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You’re now ready to run your first test. Back to your terminal, simply run npm test. You should see a result like the following:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wyWA4SoX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ma6mws4b8l3va4gb9e23.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wyWA4SoX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ma6mws4b8l3va4gb9e23.png" alt="Image description" width="880" height="463"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, all four tests passed. All test suites were executed—which makes sense, since we only have one. The total time for execution was 0.616 seconds.&lt;/p&gt;

&lt;p&gt;Now that you had a test of Jest, let’s take a step back and understand, in more detail, its syntax and vocabulary.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Vocabulary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s take a look at two of the most commonly used Jest terms that are also used in other testing tools: mock and spy. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Vocabulary: Mock&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;From the Jest documentation, we can find the following description for a Jest mock: “Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls).”&lt;/p&gt;

&lt;p&gt;In addition, we can use a mock to return whatever we want it to return. This is very useful to test all the paths in our logic because we can control if a function returns a correct value, wrong value, or even throws an error.&lt;/p&gt;

&lt;p&gt;In short, a mock can be created by assigning the following snippet of code to a function or dependency:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;jest.fn()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here’s an example of a simple mock, where we just check whether a mock has been called. We mock mockFn and call it. Thereafter, we check if the mock has been called:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following example also mocks a return value for checking specific business logic. We mock the returnsTrue function and let it return false:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const returnsTrue = jest.fn(() =&amp;gt; false);
console.log(returnsTrue()); // false;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next up, let’s explore what a spy is.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Vocabulary: Spy&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A spy has a slightly different behavior but is still comparable with a mock. Again, from the official docs, we read, “Creates a mock function similar to jest.fn() but also tracks calls to object[methodName]. Returns a Jest mock function.”&lt;/p&gt;

&lt;p&gt;What this means is that the function acts as it normally would—however, all calls are being tracked. This allows you to verify if a function has been called the right number of times and held the right input parameters.&lt;/p&gt;

&lt;p&gt;Below, you’ll find an example where we want to check if the play method of a video returns the correct result but also gets called with the right parameters. We spy on the play method of the video object.&lt;/p&gt;

&lt;p&gt;Next, we call the play method and check if the spy has been called and if the returned result is correct. Pretty straightforward! In the end, we must call the mockRestore method to reset a mock to its original implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const video = require('./video');

test('plays video', () =&amp;gt; {
const spy = jest.spyOn(video, 'play');
const isPlaying = video.play();

expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);

spy.mockRestore();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;OK, now that we know about the two most used technical terms, let’s explore the basic structure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Basics&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s take a look at some basics on writing tests with Jest.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Basics: Describe Blocks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A describe block is used for organizing test cases in logical groups of tests. For example, we want to group all the tests for a specific class. We can further nest new describe blocks in an existing describe block.&lt;/p&gt;

&lt;p&gt;To continue with the example, you can add a describe block that encapsulates all the tests for a specific function of this class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Basics: “It” or “Test” Tests&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Furthermore, we use the test keyword to start a new test case definition. The it keyword is an alias for the test keyword. Personally, I like to use it, which allows for more natural language flow of writing tests. To give an example:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;describe('Beverage()', () =&amp;gt; {&lt;br&gt;
   it('should be delicious', () =&amp;gt; {&lt;br&gt;
      expect(myBeverage.delicious).toBeTruthy();&lt;br&gt;
   });&lt;br&gt;
});&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Basics: Matchers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, let’s look at the matchers Jest exposes. A matcher is used for creating assertions in combination with the expect keyword. We want to compare the output of our test with a value we expect the function to return.&lt;/p&gt;

&lt;p&gt;Again, let’s look at a simple example where we want to check if an instance of a class is the correct class we expect. We place the test value in the expect keyword and call the exposed matcher function toBeInstanceOf() to compare the values. The test results in the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it('should be instance of Car', () =&amp;gt; {
   expect(newTruck()).toBeInstanceOf(Car);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The complete list of exposed matchers can be found in the Jest API reference.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Basics: Setup and Teardown&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It’s important we understand how to prepare and clean up a test. For example, a particular test relies on a mocked database. We don’t want to call a function to set up and clean up the mocked database for each test.&lt;/p&gt;

&lt;p&gt;To solve this problem, we can use the beforeEach and afterEach functions to avoid code duplication. Both functions allow you to execute logic before or after each test.&lt;/p&gt;

&lt;p&gt;Here’s an example of mocking a database before each test and tear it down when each test has finished.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;describe('tests with database', () =&amp;gt; {

  beforeEach(() =&amp;gt; {
    initDB()
  })

  afterEach(() =&amp;gt; {
    removeDB()
  })

  test('if country exists in database', () =&amp;gt; {
    expect(isValidCountry('Belgium')).toBe(true)
  })

})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Moreover, you can also make use of beforeAll and afterAll functions. Both functions will run before or after all tests, but only once. You can use these functions to create a new database connection object and destroy it when you’ve completed the tests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;beforeAll(() =&amp;gt; {
  return createDBConnection()
})

afterAll(() =&amp;gt; {
  return destroyDBConnection()
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, let’s take a look at snapshot testing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Basics: Snapshot Testing for React Front Ends&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;At last, the Jest documentation suggests using snapshot tests to detect UI changes. As I mentioned earlier, snapshot testing can also be applied for checking larger objects, or even the JSON response for API endpoints.&lt;/p&gt;

&lt;p&gt;Let’s take a look at an example for React where we simply want to create a snapshot for a link object. The snapshot itself will be stored with the tests and should be committed alongside code changes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it('renders correctly', () =&amp;gt; {
   const tree = renderer
      .create(&amp;lt;Link page="http://www.facebook.com"&amp;gt;Facebook&amp;lt;/Link&amp;gt;)
      .toJSON();
   expect(tree).toMatchSnapshot();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Following, the above code renders the following snapshot:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exports[`renders correctly 1`] = `
&amp;lt;a
  className="normal"
  href="http://www.facebook.com"
  onMouseEnter={[Function]}
  onMouseLeave={[Function]}
&amp;gt;
  Facebook
&amp;lt;/a&amp;gt;
`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the link object changes, this test will fail in the future. If the changes to the UI elements are correct, you should update the snapshots by storing the results in the snapshot file. You can automatically update snapshots using the Jest CLI tool by adding a “-u” flag when executing the tests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Getting Started With Jest Testing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Finally, we’ve covered all the basic elements for you to get started with Jest testing. When you’re writing your first test cases, it can feel a bit uncomfortable writing mocks. However, mocks are especially useful in unit testing because they allow you to test the business logic of your function without worrying about its dependencies.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript Hoisting Explained By Examples</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Thu, 21 Apr 2022 09:28:28 +0000</pubDate>
      <link>https://dev.to/mokadevlight/javascript-hoisting-explained-by-examples-1lmp</link>
      <guid>https://dev.to/mokadevlight/javascript-hoisting-explained-by-examples-1lmp</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Summary: in this tutorial, you’ll learn about JavaScript hoisting and how it works under the hood.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Introduction to the JavaScript hoisting&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When the JavaScript engine executes the JavaScript code, it creates the global execution context. The global execution context has two phases: creation and execution.&lt;/p&gt;

&lt;p&gt;During the creation phase, the JavaScript engine moves the variable and function declarations to the top of your code. This feature is known as hoisting in JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variable hoisting&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Variable hoisting means the JavaScript engine moves the variable declarations to the top of the script.&lt;/p&gt;

&lt;p&gt;For example, the following example declares the counter variable and initialize its value to 1:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;console.log(counter); // undefined&lt;br&gt;
var counter = 1;&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
In this example, we reference the counter variable before the declaration.&lt;/p&gt;

&lt;p&gt;However, the first line of code doesn’t cause an error. The reason is that the JavaScript engine moves the variable declaration to the top of the script.&lt;/p&gt;

&lt;p&gt;Technically, the code looks like the following in the execution phase:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;var counter;&lt;br&gt;
console.log(counter); // undefined&lt;br&gt;
counter = 1;&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;During the creation phase of the global execution context, the JavaScript engine places the variable counter in the memory and initializes its value to undefined .&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The let keyword&lt;/strong&gt;&lt;br&gt;
The following declares the variable counter with the let keyword:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;console.log(counter);&lt;br&gt;
let counter = 1;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The JavaScript issues the following error:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;"ReferenceError: Cannot access 'counter' before initialization&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The error message explains that the counter variable is already in the heap memory. However, it hasn’t been initialized.&lt;/p&gt;

&lt;p&gt;Behind the scenes, the JavaScript engine hoists the variable declarations that use the let keyword. However, it doesn't initialize the let variables.&lt;/p&gt;

&lt;p&gt;Notice that if you access a variable that doesn’t exist, the JavaScript will throw a different error:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;console.log(alien);&lt;br&gt;
let counter = 1;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here is the error:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;"ReferenceError: alien is not defined&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Function hoisting&lt;/strong&gt;&lt;br&gt;
Like variables, the JavaScript engine also hoists the function declarations. This means that the JavaScript engine also moves the function declarations to the top of the script.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 20,
y = 10;
let result = add(x, y);
console.log(result);
function add(a, b) {
return a + b;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we called the add() function before defining it. The above code is equivalent to the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function add(a, b){
return a + b;
}
let x = 20,
y = 10;
let result = add(x,y);
console.log(result);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;During the creation phase of the execution context, the JavaScript engine places the add() function declaration in the heap memory.&lt;br&gt;
To be precise, the JavaScript engine creates an object of the Function type and a function reference called add that refers to the function object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Function expressions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The following example changes the add from a regular function to a function expression:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 20,
y = 10;
let result = add(x,y);
console.log(result);
var add = function(x, y) {
return x + y;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you execute the code, the following error will occur:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;“TypeError: add is not a function&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;During the creation phase of the global execution context, the JavaScript engine creates the add variable in the memory and initializes its value to undefined.&lt;/p&gt;

&lt;p&gt;When executing the following code, the add is undefined, hence, it isn't a function:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;let result = add(x,y);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The add variable is assigned to an anonymous function only during the execution phase of the global execution context.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Arrow functions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The following example changes the add function expression to the arrow function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 20,
y = 10;
let result = add(x,y);
console.log(result);
var add = (x, y) =&amp;gt; x + y;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code also issues the same error as the function expression example because arrow functions are syntactic sugar for defining function expressions.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;“TypeError: add is not a function&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Similar to the functions expressions, the arrow functions aren’t hoisted.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;JavaScript hoisting occurs during the creation phase of the execution context that moves the variable and function declarations to the top of the script.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The JavaScript engine hoists the variables declared using the let keyword, but it doesn't initialize them as the variables declared with the var keyword.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The JavaScript engine doesn’t hoist the function expressions and arrow functions.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Originally published at &lt;a href="https://www.javascripttutorial.net"&gt;https://www.javascripttutorial.net&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Event Handling</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Thu, 21 Apr 2022 09:20:12 +0000</pubDate>
      <link>https://dev.to/mokadevlight/event-handling-56pd</link>
      <guid>https://dev.to/mokadevlight/event-handling-56pd</guid>
      <description>&lt;p&gt;It all starts with attaching event listeners to elements. Say you have a button that increments a counter each time you click it. &lt;/p&gt;

&lt;p&gt;You can add an inline onclick attribute and that will work across all browsers but will be violating the separation of concerns and the progressive enhancement.&lt;/p&gt;

&lt;p&gt;So you should strive for attaching the listener in JavaScript, outside of any markup.&lt;/p&gt;

&lt;p&gt;Say you have the following markup:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button id=”clickme”&amp;gt;Click me: 0&amp;lt;/button&amp;gt;
You can assign a function to the onclick property of the node, but you can do this only
once:
// suboptimal solution
var b = document.getElementById(‘clickme’),
count = 0;
b.onclick = function () {
count += 1;
b.innerHTML = “Click me: “ + count;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to have several functions executed on click, you cannot do it with this pattern while maintaining loose coupling.&lt;/p&gt;

&lt;p&gt;Technically you can check if onclick already&lt;br&gt;
contains a function and if so, add the existing one to your own function and replace the onclick value with your new function. But a much cleaner solution is to use the addEventListener() method.&lt;/p&gt;

&lt;p&gt;This method doesn’t exist in IE up to and including version 8, so you need attachEvent() for those browsers.&lt;/p&gt;

&lt;p&gt;Without going into all the details right now, let’s just attach a listener to our button:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var b = document.getElementById(‘clickme’);
if (document.addEventListener) { // W3C
b.addEventListener(‘click’, myHandler, false);
} else if (document.attachEvent) { // IE
b.attachEvent(‘onclick’, myHandler);
} else { // last resort
b.onclick = myHandler;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now when this button is clicked, the function myHandler() will be executed.&lt;br&gt;
Let’s have this function increment the number in the “Click me: 0” button label.&lt;br&gt;
To make it a little more interesting, let’s assume we have several buttons and a single myHandler() for all of them. Keeping a reference to each button node and a counter for the number&lt;br&gt;
will be inefficient, given that we can get that information from the event object that is created on every click.&lt;/p&gt;

&lt;p&gt;Let’s see the solution first and comment on it after:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myHandler(e) {
var src, parts;
// get event and source element
e = e || window.event;
src = e.target || e.srcElement;
// actual work: update label
parts = src.innerHTML.split(“: “);
parts[1] = parseInt(parts[1], 10) + 1;
src.innerHTML = parts[0] + “: “ + parts[1];
// no bubble
if (typeof e.stopPropagation === “function”) {
e.stopPropagation();
}
if (typeof e.cancelBubble !== “undefined”) {
e.cancelBubble = true;
}
// prevent default action
if (typeof e.preventDefault === “function”) {
e.preventDefault();
}
if (typeof e.returnValue !== “undefined”) {
e.returnValue = false;
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are four parts in the event handler function:&lt;/p&gt;

&lt;p&gt;• First, we need to gain access to the event object, which contains information about the event and the page element that triggered that event. This event object is passed to the callback event handler, but not when using the onclick property where it’s&lt;br&gt;
accessible through the global property window.event instead.&lt;br&gt;
• The second part is doing the actual work of updating the label.&lt;br&gt;
• Next is canceling the propagation of the event. This is not required in this particular example, but in general if you don’t do it, then the event bubbles up all the way to the document root or even the window object.&lt;br&gt;
Again we need to do it two ways:&lt;/p&gt;

&lt;p&gt;the W3C standard way (stopPropagation()) and then differently for IE (usingcancelBubble).&lt;/p&gt;

&lt;p&gt;• Finally, prevent the default action, if this is required.&lt;br&gt;
 Some events (clicking a link, submitting a form) have default actions, but you can prevent them by using preventDefault() (or for IE, by setting returnValue to false).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event Delegation&lt;/strong&gt;&lt;br&gt;
The event delegation pattern benefits from the event bubbling and reduces the number of event listeners attached to separate nodes.&lt;/p&gt;

&lt;p&gt;If there are 10 buttons inside a div element, you can have one event listener attached to the div as opposed to 10 listeners attached to each button.&lt;/p&gt;

&lt;p&gt;Let’s have an example with three buttons inside a div So we’re working with the following markup:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id=”click-wrap”&amp;gt;
&amp;lt;button&amp;gt;Click me: 0&amp;lt;/button&amp;gt;
&amp;lt;button&amp;gt;Click me too: 0&amp;lt;/button&amp;gt;
&amp;lt;button&amp;gt;Click me three: 0&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of attaching listeners to each button, you attach one to the “click-wrap” div.&lt;/p&gt;

&lt;p&gt;Then you can use the same myHandler() function from the previous example with only one little change: you have to filter out clicks you’re not interested in.&lt;/p&gt;

&lt;p&gt;In this case you look only for clicks on any button, so all other clicks in the same div could be ignored.&lt;/p&gt;

&lt;p&gt;The change to myHandler() would be to check if the nodeName of the source of the event is a “button”:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// …
// get event and source element
e = e || window.event;
src = e.target || e.srcElement;
if (src.nodeName.toLowerCase() !== “button”) {
return;
}
// …
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The drawback of the event delegation is the slightly more code to filter out the events that happen in the container that are not interesting for you.&lt;/p&gt;

&lt;p&gt;But the benefits — performance and cleaner code — outweigh the drawbacks significantly, so it’s a highly recommended pattern.&lt;/p&gt;

&lt;p&gt;Modern JavaScript libraries make it easy to use event delegation by providing convenient APIs.&lt;br&gt;
For example YUI3 has the method Y.delegate(), which enables you to specify a CSS selector to match the wrapper and another selector to match the nodes you’re interested in.&lt;/p&gt;

&lt;p&gt;This is convenient because your callback event handler function will actually never be called when the event happens outside the nodes you care about.&lt;br&gt;
In this case, the code to attach an event listener would be simply:&lt;/p&gt;

&lt;p&gt;Y.delegate(‘click’, myHandler, “#click-wrap”, “button”);&lt;/p&gt;

&lt;p&gt;And thanks to the abstraction of all browser differences done in YUI and the fact that the source of the event is determined for us, the callback function will be much simpler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myHandler(e) {
var src = e.currentTarget,
parts;
parts = src.get(‘innerHTML’).split(“: “);
parts[1] = parseInt(parts[1], 10) + 1;
src.set(‘innerHTML’, parts[0] + “: “ + parts[1]);
e.halt();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Good Luck&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript Closure</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Thu, 21 Apr 2022 08:37:11 +0000</pubDate>
      <link>https://dev.to/mokadevlight/javascript-closure-3c32</link>
      <guid>https://dev.to/mokadevlight/javascript-closure-3c32</guid>
      <description>&lt;p&gt;Closure is one of important concept in JavaScript. It is widely discussed and still confused concept. Let’s understand what the closure is.&lt;/p&gt;

&lt;p&gt;Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.&lt;/p&gt;

&lt;p&gt;You have learned that we can create nested functions in JavaScript. Inner function can access variables and parameters of an outer function (however, cannot access arguments object of outer function). Consider the following example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function OuterFunction() {

    var outerVariable = 1;

    function InnerFunction() {
        alert(outerVariable);
    }

    InnerFunction();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, InnerFunction() can access outerVariable.&lt;/p&gt;

&lt;p&gt;Now, as per the definition above, InnerFunction() can access outerVariable even if it will be executed separately. Consider the following example.&lt;/p&gt;

&lt;p&gt;Example: Closure&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function OuterFunction() {
    var outerVariable = 100;
    function InnerFunction() {
        alert(outerVariable);
    }
    return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc(); // 100
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;n the above example, return InnerFunction; returns InnerFunction from OuterFunction when you call OuterFunction(). A variable innerFunc reference the InnerFunction() only, not the OuterFunction(). So now, when you call innerFunc(), it can still access outerVariable which is declared in OuterFunction(). This is called Closure.&lt;/p&gt;

&lt;p&gt;A function can return another function in JavaScript. A function which is assigned to a variable is called function expression.&lt;/p&gt;

&lt;p&gt;One important characteristic of closure is that outer variables can keep their states between multiple calls. Remember, inner function does not keep the separate copy of outer variables but it reference outer variables, that means value of the outer variables will be changed if you change it using inner function.&lt;/p&gt;

&lt;p&gt;Example: Closure&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Counter() {
    var counter = 0;
    function IncreaseCounter() {
        return counter += 1;
    };
    return IncreaseCounter;
}
var counter = Counter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
alert(counter()); // 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, outer function Counter returns the reference of inner function IncreaseCounter(). IncreaseCounter increases the outer variable counter to one. So calling inner function multiple time will increase the counter to one each time.&lt;/p&gt;

&lt;p&gt;Closure is valid in multiple levels of inner functions.&lt;/p&gt;

&lt;p&gt;Example: Closure&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Counter() {

    var counter = 0;
    setTimeout( function () {
        var innerCounter = 0;
        counter += 1;
        alert("counter = " + counter);
        setTimeout( function () {
            counter += 1;
            innerCounter += 1;
            alert("counter = " + counter + ", innerCounter = " + innerCounter)
        }, 500);
    }, 1000);
};
Counter();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As per the closure definition, if inner function access the variables of outer function then only it is called closure.&lt;/p&gt;

&lt;p&gt;The following is not a closure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var Counter = (function () {
        var i = 0;
        return { counter : i += 1 };
})();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;When to use Closure?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Closure is useful in hiding implementation detail in JavaScript. In other words, it can be useful to create private variables or functions.&lt;/p&gt;

&lt;p&gt;The following example shows how to create private functions &amp;amp; variable.&lt;/p&gt;

&lt;p&gt;Example: Closure&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };   
})();
alert(counter.value()); // 0
counter.increment();
counter.increment();
alert(counter.value()); // 2
counter.decrement();
alert(counter.value()); // 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Good Luck&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>The event loop</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Thu, 21 Apr 2022 08:27:43 +0000</pubDate>
      <link>https://dev.to/mokadevlight/the-event-loop-4ao6</link>
      <guid>https://dev.to/mokadevlight/the-event-loop-4ao6</guid>
      <description>&lt;p&gt;JavaScript has a runtime model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Runtime concepts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The following sections explain a theoretical model. Modern JavaScript engines implement and heavily optimize the described semantics.&lt;/p&gt;

&lt;p&gt;Function calls form a stack of frames.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function foo(b) {
  let a = 10
  return a + b + 11
}
function bar(x) {
  let y = 3
  return foo(x * y)
}
const baz = bar(7) // assigns 42 to baz
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Order of operations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;When calling bar, a first frame is created containing references to bar's arguments and local variables.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When bar calls foo, a second frame is created and pushed on top of the first one, containing references to foo's arguments and local variables.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When foo returns, the top frame element is popped out of the stack (leaving only bar's call frame).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When bar returns, the stack is empty.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note that the arguments and local variables may continue to exist, as they are stored outside the stack — so they can be accessed by any nested functions long after their outer function has returned.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Heap&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Objects are allocated in a heap which is just a name to denote a large (mostly unstructured) region of memory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Queue&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function that gets called to handle the message.&lt;/p&gt;

&lt;p&gt;At some point during the event loop, the runtime starts handling the messages on the queue, starting with the oldest one. To do so, the message is removed from the queue and its corresponding function is called with the message as an input parameter. As always, calling a function creates a new stack frame for that function’s use.&lt;/p&gt;

&lt;p&gt;The processing of functions continues until the stack is once again empty. Then, the event loop will process the next message in the queue (if there is one).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event loop&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The event loop got its name because of how it’s usually implemented, which usually resembles:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while (queue.waitForMessage()) {
  queue.processNextMessage()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;queue.waitForMessage() waits synchronously for a message to arrive (if one is not already available and waiting to be handled).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;"Run-to-completion"&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Each message is processed completely before any other message is processed.&lt;/p&gt;

&lt;p&gt;This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be preempted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread.&lt;/p&gt;

&lt;p&gt;A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adding messages&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In web browsers, messages are added anytime an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message—likewise with any other event.&lt;/p&gt;

&lt;p&gt;The function setTimeout is called with 2 arguments: a message to add to the queue, and a time value (optional; defaults to 0). The time value represents the (minimum) delay after which the message will be pushed into the queue. If there is no other message in the queue, and the stack is empty, the message is processed right after the delay. However, if there are messages, the setTimeout message will have to wait for other messages to be processed. For this reason, the second argument indicates a minimum time—not a guaranteed time.&lt;/p&gt;

&lt;p&gt;Here is an example that demonstrates this concept (setTimeout does not run immediately after its timer expires):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const seconds = new Date().getSeconds();

setTimeout(function() {
  // prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
  console.log(`Ran after ${new Date().getSeconds() - seconds} seconds`);
}, 500)

while (true) {
  if (new Date().getSeconds() - seconds &amp;gt;= 2) {
    console.log("Good, looped for 2 seconds")
    break;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Zero delays&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Zero delay doesn't mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval.&lt;/p&gt;

&lt;p&gt;The execution depends on the number of waiting tasks in the queue. In the example below, the message "this is just a message" will be written to the console before the message in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time).&lt;/p&gt;

&lt;p&gt;The setTimeout needs to wait for all the code for queued messages to complete even though you specified a particular time limit for your setTimeout.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(function() {

  console.log('this is the start');

  setTimeout(function cb() {
    console.log('Callback 1: this is a msg from call back');
  }); // has a default time value of 0

  console.log('this is just a message');

  setTimeout(function cb1() {
    console.log('Callback 2: this is a msg from call back');
  }, 0);

  console.log('this is the end');

})();

// "this is the start"
// "this is just a message"
// "this is the end"
// "Callback 1: this is a msg from call back"
// "Callback 2: this is a msg from call back"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Several runtimes communicating together&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A web worker or a cross-origin iframe has its own stack, heap, and message queue. Two distinct runtimes can only communicate through sending messages via the postMessage method. This method adds a message to the other runtime if the latter listens to message events.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;JavaScript Patterns Book&lt;/em&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>ReactJS's components written in Typescript</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Thu, 21 Apr 2022 08:13:13 +0000</pubDate>
      <link>https://dev.to/mokadevlight/reactjss-components-written-in-typescript-6cj</link>
      <guid>https://dev.to/mokadevlight/reactjss-components-written-in-typescript-6cj</guid>
      <description>&lt;p&gt;Actually you can use ReactJS's components in Typescript as in facebook's example. Just replace 'jsx' file's extension to 'tsx':&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//helloMessage.tsx:
var HelloMessage = React.createClass({
 render: function() {
 return &amp;lt;div&amp;gt;Hello {this.props.name}&amp;lt;/div&amp;gt;;
 }
});
ReactDOM.render(&amp;lt;HelloMessage name="John" /&amp;gt;, mountNode);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But in order to make full use of Typescript's main feature (static type checking) should be done couple things:&lt;/p&gt;

&lt;p&gt;1) convert React.createClass example to ES6 Class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//helloMessage.tsx:
class HelloMessage extends React.Component {
 render() {
 return &amp;lt;div&amp;gt;Hello {this.props.name}&amp;lt;/div&amp;gt;;
 }
}
ReactDOM.render(&amp;lt;HelloMessage name="John" /&amp;gt;, mountNode);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2) next add Props and State interfaces:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface IHelloMessageProps {
name:string;
}
interface IHelloMessageState { //empty in our case } class HelloMessage extends React.Component {
constructor(){
super();
}
render() {
return
&amp;lt;div&amp;gt;Hello {this.props.name}&amp;lt;/div&amp;gt;;
}
}
ReactDOM.render(, mountNode);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now Typescript will display an error if the programmer forgets to pass props. Or if they added props that are not defined in the interface.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;ReactJSNotesForProfessionals Book&lt;/em&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Use Axios with React</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Thu, 21 Apr 2022 07:57:59 +0000</pubDate>
      <link>https://dev.to/mokadevlight/use-axios-with-react-5444</link>
      <guid>https://dev.to/mokadevlight/use-axios-with-react-5444</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;This tutorial was verified with Node.js v16.13.1, npm v8.1.4, react v17.0.2, and axios v0.24.0.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Step 1 — Adding Axios to the Project&lt;/strong&gt;&lt;br&gt;
In this section, you will add Axios to a React project you created following the How to Set up a React Project with Create React App tutorial.&lt;/p&gt;

&lt;p&gt;“npx create-react-app react-axios-example”&lt;/p&gt;

&lt;p&gt;To add Axios to the project, open your terminal and change directories into your project:&lt;/p&gt;

&lt;p&gt;“cd react-axios-example”&lt;/p&gt;

&lt;p&gt;Then run this command to install Axios:&lt;/p&gt;

&lt;p&gt;“npm install &lt;a href="mailto:axios@0.24.0"&gt;axios@0.24.0&lt;/a&gt;”&lt;/p&gt;

&lt;p&gt;Next, you will need to import Axios into the file you want to use it in.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2 — Making a GET Request&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this example, you create a new component and import Axios into it to send a GET request.&lt;/p&gt;

&lt;p&gt;Inside your React project, you will need to create a new component named PersonList.&lt;/p&gt;

&lt;p&gt;First, create a new components subdirectory in the src directory:&lt;/p&gt;

&lt;p&gt;“mkdir src/components”&lt;/p&gt;

&lt;p&gt;In this directory, create PersonList.js and add the following code to the component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res =&amp;gt; {
        const persons = res.data;
        this.setState({ persons });
      })
  }

  render() {
    return (
      &amp;lt;ul&amp;gt;
        {
          this.state.persons
            .map(person =&amp;gt;
              &amp;lt;li key={person.id}&amp;gt;{person.name}&amp;lt;/li&amp;gt;
            )
        }
      &amp;lt;/ul&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request.&lt;/p&gt;

&lt;p&gt;You use axios.get(url) with a URL from an API endpoint to get a promise which returns a response object. Inside the response object, there is data that is then assigned the value of person.&lt;/p&gt;

&lt;p&gt;You can also get other information about the request, such as the status code under res.status or more information inside of res.request.&lt;/p&gt;

&lt;p&gt;Add this component to your app.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import PersonList from './components/PersonList.js';

function App() {
  return (
    &amp;lt;div ClassName="App"&amp;gt;
      &amp;lt;PersonList/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run your application:&lt;/p&gt;

&lt;p&gt;“npm start”&lt;/p&gt;

&lt;p&gt;View the application in the browser. You will be presented with a list of 10 names.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3 — Making a POST Request&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import axios from 'axios';

export default class PersonAdd extends React.Component {
  state = {
    name: ''
  }

  handleChange = event =&amp;gt; {
    this.setState({ name: event.target.value });
  }

  handleSubmit = event =&amp;gt; {
    event.preventDefault();

    const user = {
      name: this.state.name
    };

    axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
      .then(res =&amp;gt; {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
          &amp;lt;label&amp;gt;
            Person Name:
            &amp;lt;input type="text" name="name" onChange={this.handleChange} /&amp;gt;
          &amp;lt;/label&amp;gt;
          &amp;lt;button type="submit"&amp;gt;Add&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
      &amp;lt;/div&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside the handleSubmit function, you prevent the default action of the form. Then update the state to the user input.&lt;/p&gt;

&lt;p&gt;Using POST gives you the same response object with information that you can use inside of a then call.&lt;/p&gt;

&lt;p&gt;To complete the POST request, you first capture the user input. Then you add the input along with the POST request, which will give you a response. You can then console.log the response, which should show the user input in the form.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4 — Making a DELETE Request&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import axios from 'axios';

export default class PersonRemove extends React.Component {
  state = {
    id: ''
  }

  handleChange = event =&amp;gt; {
    this.setState({ id: event.target.value });
  }

  handleSubmit = event =&amp;gt; {
    event.preventDefault();

    axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)
      .then(res =&amp;gt; {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
          &amp;lt;label&amp;gt;
            Person ID:
            &amp;lt;input type="number" name="id" onChange={this.handleChange} /&amp;gt;
          &amp;lt;/label&amp;gt;
          &amp;lt;button type="submit"&amp;gt;Delete&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
      &amp;lt;/div&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Thanks for posting.&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Use react-error-boundary to handle errors in React</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Wed, 20 Apr 2022 18:55:41 +0000</pubDate>
      <link>https://dev.to/mokadevlight/use-react-error-boundary-to-handle-errors-in-react-1adk</link>
      <guid>https://dev.to/mokadevlight/use-react-error-boundary-to-handle-errors-in-react-1adk</guid>
      <description>&lt;p&gt;What’s wrong with this code?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as React from 'react'
import ReactDOM from 'react-dom'

function Greeting({subject}) {
  return &amp;lt;div&amp;gt;Hello {subject.toUpperCase()}&amp;lt;/div&amp;gt;
}

function Farewell({subject}) {
  return &amp;lt;div&amp;gt;Goodbye {subject.toUpperCase()}&amp;lt;/div&amp;gt;
}

function App() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Greeting /&amp;gt;
      &amp;lt;Farewell /&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

ReactDOM.render(&amp;lt;App /&amp;gt;, document.getElementById('root'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you send that to production, your users are going to get the white screen of sadness:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjk0g5n9fzri8asykbrgn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjk0g5n9fzri8asykbrgn.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you run this with create-react-app’s error overlay (during development), you’ll get this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw34h38g8jshmruetqa5n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw34h38g8jshmruetqa5n.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The problem is we need to either pass a subject prop (as a string) or default the subject prop's value. Obviously, this is contrived, but runtime errors happen all of the time and that's why it's a good idea to gracefully handle such errors. So let's leave this error in for a moment and see what tools React has for us to handle runtime errors like this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;try/catch?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The naive approach to handling this kind of error would be to add a try/catch:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as React from 'react'
import ReactDOM from 'react-dom'

function ErrorFallback({error}) {
  return (
    &amp;lt;div role="alert"&amp;gt;
      &amp;lt;p&amp;gt;Something went wrong:&amp;lt;/p&amp;gt;
      &amp;lt;pre style={{color: 'red'}}&amp;gt;{error.message}&amp;lt;/pre&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

function Greeting({subject}) {
  try {
    return &amp;lt;div&amp;gt;Hello {subject.toUpperCase()}&amp;lt;/div&amp;gt;
  } catch (error) {
    return &amp;lt;ErrorFallback error={error} /&amp;gt;
  }
}

function Farewell({subject}) {
  try {
    return &amp;lt;div&amp;gt;Goodbye {subject.toUpperCase()}&amp;lt;/div&amp;gt;
  } catch (error) {
    return &amp;lt;ErrorFallback error={error} /&amp;gt;
  }
}

function App() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Greeting /&amp;gt;
      &amp;lt;Farewell /&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

ReactDOM.render(&amp;lt;App /&amp;gt;, document.getElementById('root'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That “works”:&lt;/p&gt;

&lt;p&gt;Something went wrong:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Cannot read properties of undefined (reading 'toUpperCase')&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Something went wrong:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Cannot read properties of undefined (reading 'toUpperCase')&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;But, it may be ridiculous of me, but what if I don’t want to wrap every component in my app in a try/catch block? In regular JavaScript, you can simply wrap the calling function in a try/catch and it'll catch any errors in the functions it calls. Let's try that here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as React from 'react'
import ReactDOM from 'react-dom'

function ErrorFallback({error}) {
  return (
    &amp;lt;div role="alert"&amp;gt;
      &amp;lt;p&amp;gt;Something went wrong:&amp;lt;/p&amp;gt;
      &amp;lt;pre style={{color: 'red'}}&amp;gt;{error.message}&amp;lt;/pre&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

function Greeting({subject}) {
  return &amp;lt;div&amp;gt;Hello {subject.toUpperCase()}&amp;lt;/div&amp;gt;
}

function Farewell({subject}) {
  return &amp;lt;div&amp;gt;Goodbye {subject.toUpperCase()}&amp;lt;/div&amp;gt;
}

function App() {
  try {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;Greeting /&amp;gt;
        &amp;lt;Farewell /&amp;gt;
      &amp;lt;/div&amp;gt;
    )
  } catch (error) {
    return &amp;lt;ErrorFallback error={error} /&amp;gt;
  }
}

ReactDOM.render(&amp;lt;App /&amp;gt;, document.getElementById('root'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, this doesn’t work. And that’s because we’re not the ones calling Greeting and Farewell. React calls those functions. When we use them in JSX, we're simply creating React elements with those functions as the type. Telling React that "if the App is rendered, here are the other components that will need to be called." But we're not actually calling them, so the try/catch won't work.&lt;br&gt;
I’m not too disappointed by this to be honest, because try/catch is inherently imperative and I'd prefer a declarative way to handle errors in my app anyway.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React Error Boundary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is where the Error Boundary feature comes in to play. An “Error Boundary” is a special component that you write to handle runtime errors like those above. For a component to be an Error Boundary:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It must be a class component 🙁&lt;/li&gt;
&lt;li&gt;It must implement either getDerivedStateFromError or componentDidCatch.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Luckily, we have react-error-boundary which exposes the last Error Boundary component anyone needs to write because it gives you all the tools you need to declaratively handle runtime errors in your React apps.&lt;/p&gt;

&lt;p&gt;So let’s add react-error-boundary and render the ErrorBoundary component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as React from 'react'
import ReactDOM from 'react-dom'
import {ErrorBoundary} from 'react-error-boundary'

function ErrorFallback({error}) {
  return (
    &amp;lt;div role="alert"&amp;gt;
      &amp;lt;p&amp;gt;Something went wrong:&amp;lt;/p&amp;gt;
      &amp;lt;pre style={{color: 'red'}}&amp;gt;{error.message}&amp;lt;/pre&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

function Greeting({subject}) {
  return &amp;lt;div&amp;gt;Hello {subject.toUpperCase()}&amp;lt;/div&amp;gt;
}

function Farewell({subject}) {
  return &amp;lt;div&amp;gt;Goodbye {subject.toUpperCase()}&amp;lt;/div&amp;gt;
}

function App() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ErrorBoundary FallbackComponent={ErrorFallback}&amp;gt;
        &amp;lt;Greeting /&amp;gt;
        &amp;lt;Farewell /&amp;gt;
      &amp;lt;/ErrorBoundary&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

ReactDOM.render(&amp;lt;App /&amp;gt;, document.getElementById('root'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Something went wrong:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;TypeError: Cannot read property 'toUpperCase' of undefined&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Error Recovery&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The nice thing about this is you can almost think about the ErrorBoundary component the same way you do a try/catch block. You can wrap it around a bunch of React components to handle lots of errors, or you can scope it down to a specific part of the tree to have more granular error handling and recovery. react-error-boundary gives us all the tools we need to manage this as well.&lt;/p&gt;

&lt;p&gt;Here’s a more complex example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ErrorFallback({error, resetErrorBoundary}) {
  return (
    &amp;lt;div role="alert"&amp;gt;
      &amp;lt;p&amp;gt;Something went wrong:&amp;lt;/p&amp;gt;
      &amp;lt;pre style={{color: 'red'}}&amp;gt;{error.message}&amp;lt;/pre&amp;gt;
      &amp;lt;button onClick={resetErrorBoundary}&amp;gt;Try again&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

function Bomb({username}) {
  if (username === 'bomb') {
    throw new Error('💥 CABOOM 💥')
  }
  return `Hi ${username}`
}

function App() {
  const [username, setUsername] = React.useState('')
  const usernameRef = React.useRef(null)

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;label&amp;gt;
        {`Username (don't type "bomb"): `}
        &amp;lt;input
          placeholder={`type "bomb"`}
          value={username}
          onChange={e =&amp;gt; setUsername(e.target.value)}
          ref={usernameRef}
        /&amp;gt;
      &amp;lt;/label&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;ErrorBoundary
          FallbackComponent={ErrorFallback}
          onReset={() =&amp;gt; {
            setUsername('')
            usernameRef.current.focus()
          }}
          resetKeys={[username]}
        &amp;gt;
          &amp;lt;Bomb username={username} /&amp;gt;
        &amp;lt;/ErrorBoundary&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Handle All Errors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unfortunately, there are some errors that React doesn’t/can’t hand off to our Error Boundary. To quote the React docs:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Error boundaries do not catch errors for:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Event handlers&lt;/li&gt;
&lt;li&gt;Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)&lt;/li&gt;
&lt;li&gt;Server side rendering&lt;/li&gt;
&lt;li&gt;Errors thrown in the error boundary itself (rather than its children&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Most of the time, folks will manage some error state and render something different in the event of an error, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Greeting() {
  const [{status, greeting, error}, setState] = React.useState({
    status: 'idle',
    greeting: null,
    error: null,
  })

  function handleSubmit(event) {
    event.preventDefault()
    const name = event.target.elements.name.value
    setState({status: 'pending'})
    fetchGreeting(name).then(
      newGreeting =&amp;gt; setState({greeting: newGreeting, status: 'resolved'}),
      newError =&amp;gt; setState({error: newError, status: 'rejected'}),
    )
  }

  return status === 'rejected' ? (
    &amp;lt;ErrorFallback error={error} /&amp;gt;
  ) : status === 'resolved' ? (
    &amp;lt;div&amp;gt;{greeting}&amp;lt;/div&amp;gt;
  ) : (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;label&amp;gt;Name&amp;lt;/label&amp;gt;
      &amp;lt;input id="name" /&amp;gt;
      &amp;lt;button type="submit" onClick={handleClick}&amp;gt;
        get a greeting
      &amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, doing things that way means that you have to maintain TWO ways to handle errors:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Runtime errors&lt;/li&gt;
&lt;li&gt;fetchGreeting errors&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Luckily, react-error-boundary also exposes a simple hook to help with these situations as well. Here's how you could use that to side-step this entirely:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Greeting() {
  const [{status, greeting}, setState] = React.useState({
    status: 'idle',
    greeting: null,
  })
  const handleError = useErrorHandler()

  function handleSubmit(event) {
    event.preventDefault()
    const name = event.target.elements.name.value
    setState({status: 'pending'})
    fetchGreeting(name).then(
      newGreeting =&amp;gt; setState({greeting: newGreeting, status: 'resolved'}),
      error =&amp;gt; handleError(error),
    )
  }

  return status === 'resolved' ? (
    &amp;lt;div&amp;gt;{greeting}&amp;lt;/div&amp;gt;
  ) : (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;label&amp;gt;Name&amp;lt;/label&amp;gt;
      &amp;lt;input id="name" /&amp;gt;
      &amp;lt;button type="submit" onClick={handleClick}&amp;gt;
        get a greeting
      &amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So when our fetchGreeting promise is rejected, the handleError function is called with the error and react-error-boundary will make that propagate to the nearest error boundary like usual.&lt;/p&gt;

&lt;p&gt;Alternatively, let’s say you’re using a hook that gives you the error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Greeting() {
  const [name, setName] = React.useState('')
  const {status, greeting, error} = useGreeting(name)
  useErrorHandler(error)

  function handleSubmit(event) {
    event.preventDefault()
    const name = event.target.elements.name.value
    setName(name)
  }

  return status === 'resolved' ? (
    &amp;lt;div&amp;gt;{greeting}&amp;lt;/div&amp;gt;
  ) : (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;label&amp;gt;Name&amp;lt;/label&amp;gt;
      &amp;lt;input id="name" /&amp;gt;
      &amp;lt;button type="submit" onClick={handleClick}&amp;gt;
        get a greeting
      &amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, if the error is ever set to a truthy value, then it will be propagated to the nearest error boundary.&lt;/p&gt;

&lt;p&gt;In either case, you could handle those errors like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const ui = (&lt;br&gt;
  &amp;lt;ErrorBoundary FallbackComponent={ErrorFallback}&amp;gt;&lt;br&gt;
    &amp;lt;Greeting /&amp;gt;&lt;br&gt;
  &amp;lt;/ErrorBoundary&amp;gt;&lt;br&gt;
)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And now that’ll handle your runtime errors as well as the async errors in the fetchGreeting or useGreeting code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Good luck.&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Tailwind CSS</title>
      <dc:creator>MokaDevLight</dc:creator>
      <pubDate>Tue, 19 Apr 2022 08:59:15 +0000</pubDate>
      <link>https://dev.to/mokadevlight/tailwind-css-i9p</link>
      <guid>https://dev.to/mokadevlight/tailwind-css-i9p</guid>
      <description>&lt;p&gt;CSS technology was one of the biggest game-changers in web development. It allowed for more styling capabilities and freedom. As CSS grew, so did its complexity. CSS in retrospect is not challenging to write, but it can be tricky to implement.&lt;/p&gt;

&lt;p&gt;The next phase in CSS was the development of libraries and frameworks. One of the most famous examples of CSS frameworks is Bootstrap.&lt;/p&gt;

&lt;p&gt;Frameworks like Bootstrap have one major disadvantage. Due to increased growth and usage, they became too big and offer less control over their styles. Learning frameworks like Bootstrap has become increasingly challenging because developers have to learn hundreds of classes.&lt;/p&gt;

&lt;p&gt;In this article, we will cover:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What Tailwind CSS is.&lt;/li&gt;
&lt;li&gt;Different ways to install and configure Tailwind CSS.&lt;/li&gt;
&lt;li&gt;How to use utility-based classes over regular pre-written classes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To follow along with this tutorial, a basic understanding of HTML and CSS is necessary. Any prior experience with a CSS framework is an added advantage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Tailwind CSS&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Tailwind is a CSS framework created by Adam Wathan. Unlike other frameworks, it does not come prebuilt with classes to add to the HTML tags. Instead, it uses a different approach. It brings a much lower level of control by using utility-based classes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Installation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s get right into it and install Tailwind CSS so we can discover more about it. There are two ways to install Tailwind CSS, depending on your use case.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Method 1: Using the CDN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using a CDN is the most common way of using any CSS framework, and Tailwind CSS is no exception. We add the Tailwind CSS file from the CDN in form of a link in the HTML page’s head section.&lt;/p&gt;

&lt;p&gt;First, create a HTML file and give it a name. We will name ours index.html. Then inside it, Write the boilerplate HTML code and add the CDN as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8" /&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;title&amp;gt;Section Tailwind Demo&amp;lt;/title&amp;gt;
    &amp;lt;link
      href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css"
      rel="stylesheet"
    /&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great. We have Tailwind CSS installed in our project.&lt;br&gt;
Note: Installing Tailwind CSS by using its CDN has a few drawbacks such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You cannot add any third-party plugins.&lt;/li&gt;
&lt;li&gt;Since Tailwind CSS fetches files when the file loads, you cannot purge unused files.&lt;/li&gt;
&lt;li&gt;You cannot tinker with some configurations like the theme.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Method 2: Using npm&lt;/strong&gt;&lt;br&gt;
Using the npm method bestows the full experience of Tailwind CSS. It is a common installation method because most JavaScript frameworks use a similar approach. There are minimal differences in the installation process, depending on the framework’s architecture.&lt;/p&gt;

&lt;p&gt;Let’s get started.&lt;br&gt;
First, let’s create a directory where we will be working.&lt;br&gt;
In your terminal, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir section-tailwind-demo &amp;amp;&amp;amp; cd section-tailwind-demo
npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, let’s install Tailwind CSS. We also need to install some other packages alongside it. We need PostCSS because Tailwind CSS relies on a preprocessor to bundle the CSS. Tailwind uses a PostCSS plugin called autoprefixer to transpile the CSS into vanilla CSS.&lt;/p&gt;

&lt;p&gt;In the terminal run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install tailwindcss@latest postcss@latest autoprefixer@latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The command above will install all the dependencies we need. Next, we have to create a script to configure Tailwind CSS and PostCss. To generate the scripts, we make use of the tailwind cli utility provided by Tailwind CSS.&lt;/p&gt;

&lt;p&gt;In the terminal run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx tailwind init -p
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will generate two files, tailwind.config.js and postcss.config.js. The tailwind.config.js looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The postcss.config.js file should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have successfully set up the environment, let’s setup Tailwind CSS in our project.&lt;/p&gt;

&lt;p&gt;First, create two files — an HTML file called index.html and a stylesheet called style.css.&lt;/p&gt;

&lt;p&gt;The HTML part can have the basic boilerplate syntax at the beginning of the article. In the CSS file, we need to inform autoprefixer that we will use Tailwind CSS.&lt;/p&gt;

&lt;p&gt;We do this by importing the Tailwind CSS files, as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@tailwind base;
@tailwind components;
@tailwind utilities;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, we need to build our Tailwind CSS, so in the terminal run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx tailwindcss-cli@latest build -o css/tailwind.css
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will create a tailwind.css file in the CSS folder. The -o in the command stands for the output path, and we specified that our output file would be in the &lt;em&gt;css/tailwind.css&lt;/em&gt; path.&lt;/p&gt;

&lt;p&gt;Note: You do not need to have a CSS file to work with that command, it will still generate the Tailwind CSS file. You may, however, need the style.css file to add custom styles, write Tailwind CSS in that file, or mix Tailwind CSS with custom CSS.&lt;/p&gt;

&lt;p&gt;A different way of processing the CSS is to do it in production by adding a script in the package.json. We will use the postcss cli to run the operation during build time.&lt;/p&gt;

&lt;p&gt;To do this, let’s install PostCSS CLI.&lt;/p&gt;

&lt;p&gt;Run this in the terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install postcss-cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we add the build script in the package.json like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
 "build": "postcss style.css -o css/tailwind.css"
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, when you run npm run build it should compile the Tailwind CSS file into a CSS folder, as we wanted.&lt;/p&gt;

&lt;p&gt;We then need to add our Tailwind CSS file to the HTML like we would a regular CSS file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8" /&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;title&amp;gt;Document&amp;lt;/title&amp;gt;
    &amp;lt;link rel="stylesheet" href="css/tailwind.css" /&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Like that, we have everything set up.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Working with utility classes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To show and explain how utility classes work, let’s create a button using Tailwind CSS. This will show how Tailwind CSS affects the HTML elements.&lt;/p&gt;

&lt;p&gt;Within the Body tags in the HTML page, add:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button&amp;gt;Section&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s add some classes to our button because it looks plain. In Tailwind CSS, the color value ranges depending on the color intensity from 100 to 900. The utility class for the background is bg. To make our button’s background a faint shade of green, we add the class bg-green-100.&lt;/p&gt;

&lt;p&gt;Next, let’s style the text in the button. For this, we use the utility class text. Color rules remain, hence to add text to the color, we add the class text-green-100.&lt;/p&gt;

&lt;p&gt;Our button is looking good so now let’s add some padding. For padding, the syntax is quite straightforward. It’s the &lt;em&gt;property, size, then the value&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;This applies to all size and spacing properties, like margin, for example. To add padding on the bottom, it would be pb-8. These values range from 0 to 64. To see how ranges work in-depth, check the documentation.&lt;/p&gt;

&lt;p&gt;In our example, our padding will be py-2 for the top and the bottom and px-6 for the left and right. Let’s add some margin on the top with my-20 and some on the left with mx-20.&lt;/p&gt;

&lt;p&gt;Now, let’s make the button more rounded with the rounded utility. You can find a full list of border-radius utilities and all their classes in the documentation. We will use the border-radius of 0.5em, which corresponds to rounded-lg.&lt;/p&gt;

&lt;p&gt;Finally, let’s add some hover magic to make the button more lively. To do so, we add the classes hover:hover:bg-green-600 and &lt;br&gt;
hover:text-green-200.&lt;/p&gt;

&lt;p&gt;With that, we have styled our button with no CSS at all. The critical thing to take away is how much control Tailwind CSS gives you over the styling and elements. To get the full code for the tutorial.&lt;/p&gt;

&lt;p&gt;Our final code looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8" /&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;title&amp;gt;Section-Tailwind-Demo&amp;lt;/title&amp;gt;
    &amp;lt;link rel="stylesheet" href="css/tailwind.css" /&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;button
      type="button"
      class="hover:bg-green-600 hover:text-green-200 bg-green-100 text-green-700 mx-20 my-20 px-6 py-2 rounded-lg"
    &amp;gt;
      Section
    &amp;lt;/button&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Good Luck&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
