{"componentChunkName":"component---src-gatsby-theme-try-ghost-templates-post-js","path":"/react-hooks-tutorial-create-a-number-trivia-generator-website/","result":{"data":{"customPost":{"id":"Ghost__Post__6127ba1b3ed159214d382e72","title":"React Hooks Tutorial — Create a Number Trivia Generator Website","slug":"react-hooks-tutorial-create-a-number-trivia-generator-website","featured":false,"feature_image":"https://res-1.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_-Ijet6kVJqGgul6adezDLQ.png","excerpt":"In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that generates number trivia.","custom_excerpt":"In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that generates number trivia.","visibility":"public","created_at_pretty":"10 Nov 2020","published_at_pretty":"16 Apr 2019","updated_at_pretty":"10 Nov 2020","created_at":"2020-11-10T07:34:40.000+00:00","published_at":"2019-04-16T07:34:00.000+00:00","updated_at":"2020-11-10T08:20:26.000+00:00","meta_title":null,"meta_description":null,"og_description":null,"og_image":null,"og_title":null,"twitter_description":null,"twitter_image":null,"twitter_title":null,"authors":[{"slug":"shahed","url":"https://backend.shahednasser.com/author/shahed/","name":"Shahed Nasser","bio":null,"cover_image":null,"profile_image":"https://backend.shahednasser.com/content/images/2022/03/IMG_0591.jpg","location":null,"website":null,"twitter":null,"facebook":null,"meta_title":null,"meta_description":null,"coverImageSharp":null,"profileImageSharp":null}],"primary_author":{"slug":"shahed","url":"https://backend.shahednasser.com/author/shahed/","name":"Shahed Nasser","bio":null,"cover_image":null,"profile_image":"https://backend.shahednasser.com/content/images/2022/03/IMG_0591.jpg","location":null,"website":null,"twitter":null,"facebook":null,"meta_title":null,"meta_description":null,"coverImageSharp":null,"profileImageSharp":{"base":"IMG_0591.jpg","publicURL":"/static/ceb49c3c631485453e71e00d7f84b069/IMG_0591.jpg","imageMeta":{"width":1182,"height":1179},"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAMEAQL/xAAWAQEBAQAAAAAAAAAAAAAAAAADBAL/2gAMAwEAAhADEAAAAdXiFM6i0CohUWXoKn//xAAcEAACAgIDAAAAAAAAAAAAAAACAwESBBEhM0H/2gAIAQEAAQUCWySE3WEr7SzbXjAj4iKty+sOQ//EABYRAQEBAAAAAAAAAAAAAAAAAAERIP/aAAgBAwEBPwEhj//EABQRAQAAAAAAAAAAAAAAAAAAACD/2gAIAQIBAT8BH//EAB4QAAIBBAMBAAAAAAAAAAAAAAABIRESMUECECJx/9oACAEBAAY/ApVGWvOjzgtUwLlTZA0sdL4f/8QAHBAAAwACAwEAAAAAAAAAAAAAAAERITFBkbHB/9oACAEBAAE/IahkCy+N2GwZpjQiJHJCspUFY0QrSi+HqiW2rgf/2gAMAwEAAgADAAAAEPw3/wD/xAAYEQEBAAMAAAAAAAAAAAAAAAAAARExQf/aAAgBAwEBPxCtjDqP/8QAFxEBAQEBAAAAAAAAAAAAAAAAAQAxEf/aAAgBAgEBPxBFus6Tt//EAB8QAQEAAgIBBQAAAAAAAAAAAAERACExQWFRcYGR0f/aAAgBAQABPxAuaBPPzkO1wyX7F4wkwXanfZrFQgeqE9JgS14vVOvrERIJomVBKwt2jebAeP0yVa8h1n//2Q==","aspectRatio":1,"src":"/static/ceb49c3c631485453e71e00d7f84b069/31709/IMG_0591.jpg","srcSet":"/static/ceb49c3c631485453e71e00d7f84b069/f340b/IMG_0591.jpg 28w,\n/static/ceb49c3c631485453e71e00d7f84b069/22d64/IMG_0591.jpg 55w,\n/static/ceb49c3c631485453e71e00d7f84b069/31709/IMG_0591.jpg 110w,\n/static/ceb49c3c631485453e71e00d7f84b069/aa249/IMG_0591.jpg 165w,\n/static/ceb49c3c631485453e71e00d7f84b069/0dc33/IMG_0591.jpg 220w,\n/static/ceb49c3c631485453e71e00d7f84b069/d8257/IMG_0591.jpg 1182w","srcWebp":"/static/ceb49c3c631485453e71e00d7f84b069/8678c/IMG_0591.webp","srcSetWebp":"/static/ceb49c3c631485453e71e00d7f84b069/59cda/IMG_0591.webp 28w,\n/static/ceb49c3c631485453e71e00d7f84b069/7da75/IMG_0591.webp 55w,\n/static/ceb49c3c631485453e71e00d7f84b069/8678c/IMG_0591.webp 110w,\n/static/ceb49c3c631485453e71e00d7f84b069/f282e/IMG_0591.webp 165w,\n/static/ceb49c3c631485453e71e00d7f84b069/a7b21/IMG_0591.webp 220w,\n/static/ceb49c3c631485453e71e00d7f84b069/63099/IMG_0591.webp 1182w","sizes":"(max-width: 110px) 100vw, 110px"}}}},"primary_tag":null,"tags":[],"plaintext":"Hooks have been officially added to React as of React 16.8. One of the main\nbenefits of Hooks in React is that you can use state and effect (which is\ngenerally a combination of different life cycles into one) in a component\nwithout creating a class.\n\nIn this tutorial, you’ll learn how to exactly use hooks in React. We will build\na simple website that gives the user some options to pick from in order to\ngenerate some random number trivia.\n\nYou can check out the demo for the website here\n[http://numbers-trivia.surge.sh/], and the source code on the GitHub repository\n[https://github.com/shahednasser/numbers-trivia].\n\nLet’s first start by creating a react app. Since our website will be very\nsimple, we will use the create-react-app command. If you don’t have it\ninstalled, you can install it using npm.\n\nRun the following in your terminal or CMD:\n\nnpm i -g create-react-app\n\nThis will install create-react-app globally.\n\nNow we can create our React app:\n\ncreate-react-app numbers-trivia\n\nRunning this command will create a directory in the working directory with the\nname you supply for the React app. I named it numbers-trivia but you can call it\nwhatever you want.\n\nInside that directory, it will also install all the packages and files needed to\nrun the website. It will install packages like react, react-dom, react-scripts \nand more.\n\nOnce it’s done, change into the newly created directory and start the server:\n\ncd numbers-trivia\nnpm start\n\nOnce you start the server, a web page of your website in your favorite browser\nwill open. You will see a page with just the logo and a link to learn React.\n\nBefore we start changing the page, if you are not familiar with React, let’s\ntake a look at the structure of our React app. It should look something like\nthis:\n\nIn our root directory, we will find a bunch of directories. node_modules holds\nall the packages React needs to run and any package you might add. public holds\nthe files our server serves.\n\nThe directory that we will spend most of our time in is the src directory. This\ndirectory will hold all of our React components.\n\nAs you can see there are a bunch of files in that directory. index.js is\nbasically the file that renders our highest React component.\n\nWe only have one React component right now which is in App.js. If you open it,\nyou will find the code that renders the logo with the link to learn React that\nyou currently see on the website.\n\nSo, in order to see how changing our App component will change the content of\nthe website, let’s modify the code by removing the current content and replacing\nit with our favorite phrase: “Hello, World!”\n\nimport React, { Component } from 'react' \nimport logo from './logo.svg' \nimport './App.css'  \nclass App extends Component {\n   render() {\n     return (\n       <div className=\"App\">\n         <header className=\"App-header\">\n           <h1>Hello, World!</h1>\n         </header>\n       </div>\n     )\n   }\n }\nexport default App\n\nWe just replaced the content of the header element. Now, if your server is still\nrunning you will see that your page updated without you refreshing it, and you\nwill see that the previous content is replaced with Hello, World!\n\nSo now we know how and where we should edit our React components in order to get\nthe result we want. We can go ahead and start with our objective.\n\nWhat we’ll do for this website is the following:\n\n 1. Show a welcome message the first time the user opens the website, then\n    replace it with a message prompting the user to try the generator.\n 2. Render a form with text and select inputs. The text input is where the user\n    can enter the number they want to see trivia about, and the select input\n    will provide the user with options related to the trivia.\n 3. On submitting the form, send a request to this API [http://numbersapi.com/] \n    to fetch the trivia we need.\n 4. Render the trivia for the user to see it.\n\nLet’s start by organizing our directory structure first. In React it’s good\npractice to create a directory inside src holding all the components. We’ll\ncreate a directory called components. Once you create the directory, move App.js \ninto there. We will also create a directory called styles and move App.css and \nindex.css into it.\n\nWhen you do that, you will need to change the imports in your files as\nfollowing:\n\n 1. in index.js:\n\nimport React from 'react'; \nimport ReactDOM from 'react-dom'; \nimport '../styles/index.css'; \nimport App from './components/App'; \nimport  as serviceWorker from './serviceWorker';\n\n2. in App.js:\n\nimport React, { Component } from 'react'; \nimport logo from './logo.svg'; \nimport '../styles/App.css';\n\nOur directory structure should look like this now:\n\nWe will go ahead now and start building our webpage.\n\nThe first thing in our objectives list is showing a welcome message when the\nuser first opens the webpage. It will show up for 3 seconds, and then changes to\nanother message that will prompt the user to try out the trivia generator.\n\nWithout hooks, this could be done by using React’s lifecycle method \ncomponentDidMount which runs right after the component first renders.\n\nNow, we can use the effect hook [https://reactjs.org/docs/hooks-effect.html] \ninstead. It will look something like this:\n\nuseEffect(() => {\n  //perform something post render\n});\n\nThe function you pass to useEffect will be executed after every render. This\ncombines the lifecycles methods componentDidMount and componentDidUpdate into\none.\n\nWhat if you want to do something just after the first time the component\nrenders, like in componentDidMount? You can do this by passing a second\nparameter to useEffect.\n\nuseEffect accepts an array as a second parameter. This parameter is used as a\ncondition on when to perform the passed function. So, let’s say you want to\nchange a counter only after the variable counter changes, you can do it like so:\n\nuseEffect(() => document.title = `You have clicked ${counter} times`, [counter]);\n\nThis way, the function passed to useEffect will run after render only if the\nvalue for counter changes.\n\nIf we want the function to run only after the first render, we can do that by\npassing an empty array as the second parameter.\n\nLet’s come back now to what we want to do. We want to show a welcome message\nwhen the user first opens the page, then change that message after 3 seconds. We\ncan do that by adding the following inside App.js:\n\nimport React, {useEffect} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n   useEffect(() => {\n     setTimeout(() => {\n       let welcomeMessage = document.getElementById(\"welcomeMessage\");\n       welcomeMessage.innerHTML = \"Try Out Our Trivia Generator!\";\n     }, 3000);\n   }, []);\n   return (\n     <div className=\"App\">\n       <header className=\"App-header\">\n         <h1 id=\"welcomeMessage\">Welcome to Numbers Trivia!</h1>\n         <Form />\n       </header>\n     </div>\n   ); }  \nexport default App;\n\nHere’s what we’re doing:\n\n 1. Line 1: We added an import for useEffect\n 2. Line 4: We changed our class component into a function component\n 3. Line 5–10: we added an effect to our function component. This effect sets a\n    timer after 3 seconds that will change the text in the element with the id \n    welcomeMessage. Because we passed an empty array to useEffect, this effect\n    will only run once.\n 4. Line 11–17: We replaced the previous code in App.js to render an h1 element\n    having the id welcomeMessage, which is our target element.\n\nOkay, now go to our web page and see the changes. At first, the welcome message\n“Welcome to Numbers Trivia!” will show up, then 3 seconds later it will change\ninto “Try Out Our Trivia Generator!” We just used a React Hook!\n\nNext, let’s create our form input elements. To do that, we will create a new\nReact component called Form. Create in the directory components the file \nForm.js. For now, it will just include the following:\n\nimport React from 'react';  \nfunction Form(props){\n}\nexport default Form;\n\nThis will create the new React component. We’re just importing React, then we’re\ncreating a function called Form. As we said earlier in the tutorial, with the\nuse of hooks we can now create components as stateful functions rather than\nclasses. And in the last line, we’re exporting Form in order to import it in\nother files.\n\nIn the form, we will have a text input and select elements. This is based on the\nAPI we’re using. In the API, two parameters can be sent:\n\n 1. number: the number you want to get the trivia for. It can be an integer, a\n    date of the form month/day, or the keyword random which will retrieve facts\n    about a random number.\n 2. type: the type of information you want to get. There are a few types: math,\n    date, year, or, the default, trivia.\n\nWe will consider the text input element as optional. If the user does not enter\na number or a date, we will send the keyword random for the number element.\n\nLet’s add the following code inside the Form function in order to render our\nform:\n\nfunction Form(props){\n  return (<form>\n             <div>\n              <input type=\"text\" name=\"number\" placeholder=\"Enter a number (Optional)\" />\n             </div>\n             <div>\n              <select name=\"type\">\n               <option value=\"trivia\">Trivia</option>\n               <option value=\"math\">Math</option>\n               <option value=\"date\">Date</option>\n               <option value=\"year\">Year</option>\n              </select>\n             </div>\n             <button type=\"submit\">Generate</button>\n            </form>); \n}\n\nThis will create the form with the text input and select and button elements.\n\nAfter that, we need to import and render the Form component in our App \ncomponent:\n\nimport React, {useEffect} from 'react';\nimport Form from './Form';\nimport '../styles/App.css';  \nfunction App() {\n   useEffect(() => {\n     setTimeout(() => {\n       let welcomeMessage = document.getElementById(\"welcomeMessage\");\n       welcomeMessage.innerHTML = \"Try Out Our Trivia Generator!\";\n     }, 3000);\n   }, []);\n   return (\n     <div className=\"App\">\n       <header className=\"App-header\">\n         <h1 id=\"welcomeMessage\">Welcome to Numbers Trivia!</h1>\n         <Form />\n       </header>\n     </div>\n   );\n }\nexport default App;\n\nWe have changed the imports to import our Form component, and we added <Form /> \nto render the form.\n\nLet’s also add more styles just to make our form look a little better. Add the\nfollowing at the end of App.css:\n\nform {\n   font-size: 15px;\n}  \nform input, form select {\n   padding: 5px;\n}  \nform select {\n   width: 100%; \n}  \nform div {\n   margin-bottom: 8px;\n}\n\nIf you refresh the page now, you will find it has changed and now it’s showing\nour form.\n\nNow, we need to add some logic to our form. On Submit, we need to get the values\nof our input elements, then call the API to retrieve the results.\n\nTo handle form elements and their values, you need to use the state of the\ncomponent. You make the value of the element equal to a property in the state of\nthe component.\n\nBefore hooks, in order to get the value in the state you would have to use \nthis.state.value, and then to set the state, you will need to call this.setState\n.\n\nNow, you can use the state hook. The state hook is the useState function. It\naccepts one argument, which is the initial value, and it returns a pair of\nvalues: the current state and a function that updates it. Then, you will be able\nto access the current state using the first returned value, and update it using\nthe second returned value which is the function.\n\nHere’s an example:\n\nconst [count, setCount] = useState(0);\n\nin this example, we call the useState hook and pass it 0, and we set the\nreturned value equal to count and setCount. This means that we have created\nstate variable called count. Its initial value is 0, and to change its value we\ncan use setCount.\n\nFor our Form component, we need two state variables, one for the text input\nwhich we will call number, and one for the select input which we will call type.\nThen, on change event for these two input elements, we will change the values\nfor number and type using the function returned by setState.\n\nOpen our Form component and change it to the following:\n\nimport React, { useState } from 'react';\nfunction Form(props){\n  let [number, setNumber] = useState(\"random\");\n  let [type, setType] = useState(\"trivia\");\n  function onNumberChanged(e){\n    let value = e.target.value.trim();\n    if(!value.length){\n      setNumber(\"random\"); //default value\n    } else {\n      setNumber(value);\n    }\n  }\n  function onTypeChanged(e){\n    let value = e.target.value.trim();\n    if(!value.length){\n      setType(\"trivia\"); //default value\n    } else {\n      setType(value);\n    }\n  }\n  return (<form>\n            <div>\n              <input type=\"text\" name=\"number\" placeholder=\"Enter a number (Optional)\" value={number} onChange={onNumberChanged} />\n            </div>\n            <div>\n              <select name=\"type\" value={type} onChange={onTypeChanged}>\n                <option value=\"trivia\">Trivia</option>\n                <option value=\"math\">Math</option>\n                <option value=\"date\">Date</option>\n                <option value=\"year\">Year</option>\n              </select>\n            </div>\n            <button type=\"submit\">Generate</button>\n</form>);\n}\nexport default Form;\n\n 1. Line 1: add an import for useState hook.\n 2. Line 3–4: create two state variables number and type using useState . Here\n    we pass random as the initial value for number, and trivia as initial value\n    for type because they are the default values for the parameters in the API.\n 3. Line 5–10: implement input change handler functions for both text and select\n    inputs, where we change the value of the state variables using the functions\n    returned by useState . If the value is unset, we automatically change the\n    values to the default value.\n 4. Line 13: pass the onNumberChanged function to onChange event for text input.\n 5. Line 16: pass the onTypeChanged function to onChange event for select input.\n\nIn addition, let’s go back to our App component to modify it and use states.\nInstead of modifying our welcome message by changing the innerHTML of the\nelement, we will use a state. Our App component should now be like this:\n\nimport React, {useEffect, useState} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n  const [ welcomeMessage, setWelcomeMessage ] = useState(\n    \"Welcome to Numbers Trivia!\",\n  );\nuseEffect(() => {\n    setTimeout(() => {\n      setWelcomeMessage(\"Try Out Our Trivia Generator!\");\n    }, 3000);\n  }, []);\nreturn (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <h1>{welcomeMessage}</h1>\n      </header>\n      <Form/>\n    </div>\n  );\n}\nexport default App;\n\nNow, we are using useState to declare and initialize our welcome message. It\nwill return welcomeMessage , our state variable, and setWelcomeMessage , which\nwe will use to change the value of welcomeMessage after 3 seconds from “Welcome\nto Numbers Trivia!” to “Try Out Our Trivia Generator!”\n\nWhat’s left now is to add a function to handle the form’s onSubmit event. On\nsubmit, we will send a request to the API with our parameters, then display the\nresult.\n\nIn order to perform the request, we need to install axios\n[https://github.com/axios/axios]:\n\nnpm i axios\n\nThen, require axios at the beginning of Form.js:\n\nconst axios = require('axios');\n\nNow, add the following function below onTypeChanged in our Form component:\n\nfunction onSubmit(e){\n  e.preventDefault();\n  axios.get('http://numbersapi.com/' + number + '/' + type)\n       .then(function(response){\n         let elm = document.getElementById('result');\n         elm.innerHTML = response.data;\n       }).catch(function(e){\n         console.log(\"error\", e); //simple error handling\n       });\n}\n\nWe’re just performing a request to the API, passing the number and type then\ndisplaying the result in an element of id result (which we will add in a\nminute). In case of an error, we’re just displaying it in the console just as a\nsimple error handling.\n\nNow, let’s add this function as the handler for the form onSubmit event in the\nreturn statement in Form.js:\n\n<form onSubmit={onSubmit}>\n\nThe only thing left is to add the #result element. We can add it in App.js \nbefore <Form /> :\n\n<div id=\"result\" style={{marginBottom: '15px'}}></div>\n\nAlright, now go to your website and discover all new trivia about numbers!\n\n\n--------------------------------------------------------------------------------\n\nConclusion\nYou just created a React app and used some React Hooks! Of course, there’s still\nmore to explore and learn, so be sure to head to the docs\n[https://reactjs.org/docs/hooks-intro.html] to learn more about React Hooks.","html":"<p>Hooks have been officially added to React as of React 16.8. One of the main benefits of Hooks in React is that you can use state and effect (which is generally a combination of different life cycles into one) in a component without creating a class.</p><p>In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that gives the user some options to pick from in order to generate some random number trivia.</p><p>You can check out the demo for the website <a href=\"http://numbers-trivia.surge.sh/\" rel=\"noopener nofollow\">here</a>, and the source code on the <a href=\"https://github.com/shahednasser/numbers-trivia\" rel=\"noopener nofollow\">GitHub repository</a>.</p><p>Let’s first start by creating a react app. Since our website will be very simple, we will use the <code>create-react-app</code> command. If you don’t have it installed, you can install it using <code>npm</code><strong><strong>.</strong></strong></p><p>Run the following in your terminal or CMD:</p><pre><code class=\"language-Shell\">npm i -g create-react-app</code></pre><p>This will install <code>create-react-app</code> globally.</p><p>Now we can create our React app:</p><pre><code class=\"language-Shell\">create-react-app numbers-trivia</code></pre><p>Running this command will create a directory in the working directory with the name you supply for the React app. I named it <strong><strong>numbers-trivia</strong></strong> but you can call it whatever you want.</p><p>Inside that directory, it will also install all the packages and files needed to run the website. It will install packages like <strong><strong>react</strong></strong>, <strong><strong>react-dom</strong></strong>, <strong><strong>react-scripts</strong></strong> and more.</p><p>Once it’s done, change into the newly created directory and start the server:</p><pre><code class=\"language-Shell\">cd numbers-trivia\nnpm start</code></pre><p>Once you start the server, a web page of your website in your favorite browser will open. You will see a page with just the logo and a link to learn React.</p><p>Before we start changing the page, if you are not familiar with React, let’s take a look at the structure of our React app. It should look something like this:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_R1irPlPj9UsboCM_KI5CgA.png\" class=\"kg-image\" alt loading=\"lazy\"></figure><p>In our root directory, we will find a bunch of directories. <strong><strong>node_modules </strong></strong>holds all the packages React needs to run and any package you might add. <strong><strong>public </strong></strong>holds the files our server serves.</p><p>The directory that we will spend most of our time in is the <strong><strong>src</strong></strong> directory. This directory will hold all of our React components.</p><p>As you can see there are a bunch of files in that directory. <strong><strong>index.js</strong></strong> is basically the file that renders our highest React component.</p><p>We only have one React component right now which is in <strong><strong>App.js. </strong></strong>If you open it, you will find the code that renders the logo with the link to learn React that you currently see on the website.</p><p>So, in order to see how changing our App component will change the content of the website, let’s modify the code by removing the current content and replacing it with our favorite phrase: “Hello, World!”</p><pre><code class=\"language-JS\">import React, { Component } from 'react' \nimport logo from './logo.svg' \nimport './App.css'  \nclass App extends Component {\n   render() {\n     return (\n       &lt;div className=\"App\"&gt;\n         &lt;header className=\"App-header\"&gt;\n           &lt;h1&gt;Hello, World!&lt;/h1&gt;\n         &lt;/header&gt;\n       &lt;/div&gt;\n     )\n   }\n }\nexport default App</code></pre><p>We just replaced the content of the <strong><strong>header</strong></strong> element. Now, if your server is still running you will see that your page updated without you refreshing it, and you will see that the previous content is replaced with <strong><strong>Hello, World!</strong></strong></p><p>So now we know how and where we should edit our React components in order to get the result we want. We can go ahead and start with our objective.</p><p>What we’ll do for this website is the following:</p><ol><li>Show a welcome message the first time the user opens the website, then replace it with a message prompting the user to try the generator.</li><li>Render a form with <strong><strong>text </strong></strong>and <strong><strong>select</strong></strong> inputs. The <strong><strong>text </strong></strong>input is where the user can enter the number they want to see trivia about, and the <strong><strong>select </strong></strong>input will provide the user with options related to the trivia.</li><li>On submitting the form, send a request to <a href=\"http://numbersapi.com/\" rel=\"noopener nofollow\">this API</a> to fetch the trivia we need.</li><li>Render the trivia for the user to see it.</li></ol><p>Let’s start by organizing our directory structure first. In React it’s good practice to create a directory inside <strong><strong>src</strong></strong> holding all the components. We’ll create a directory called <strong><strong>components</strong></strong>. Once you create the directory, move <strong><strong>App.js</strong></strong> into there. We will also create a directory called <strong><strong>styles</strong></strong> and move <strong><strong>App.css </strong></strong>and <strong><strong>index.css </strong></strong>into it.</p><p>When you do that, you will need to change the imports in your files as following:</p><ol><li>in <strong><strong>index.js:</strong></strong></li></ol><pre><code class=\"language-JS\">import React from 'react'; \nimport ReactDOM from 'react-dom'; \nimport '../styles/index.css'; \nimport App from './components/App'; \nimport  as serviceWorker from './serviceWorker';</code></pre><p>2. in <strong><strong>App.js:</strong></strong></p><pre><code class=\"language-JS\">import React, { Component } from 'react'; \nimport logo from './logo.svg'; \nimport '../styles/App.css';</code></pre><p>Our directory structure should look like this now:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_Aqgelb3qbhJiESUbGGNUoQ.png\" class=\"kg-image\" alt loading=\"lazy\"></figure><p>We will go ahead now and start building our webpage.</p><p>The first thing in our objectives list is showing a welcome message when the user first opens the webpage. It will show up for 3 seconds, and then changes to another message that will prompt the user to try out the trivia generator.</p><p>Without hooks, this could be done by using React’s lifecycle method <code>componentDidMount</code><em><em> </em></em>which runs right after the component first renders.</p><p>Now, we can use the <a href=\"https://reactjs.org/docs/hooks-effect.html\" rel=\"noopener nofollow\"><em><em>effect hook</em></em></a><em><em> </em></em>instead. It will look something like this:</p><pre><code class=\"language-JS\">useEffect(() =&gt; {\n  //perform something post render\n});</code></pre><p>The function you pass to <code>useEffect</code> will be executed after every render. This combines the lifecycles methods <code>componentDidMount</code><strong><strong> </strong></strong>and <code>componentDidUpdate</code> into one.</p><p>What if you want to do something just after the first time the component renders, like in <code>componentDidMount</code>? You can do this by passing a second parameter to <code>useEffect</code>.</p><p><code>useEffect</code><strong><strong> </strong></strong>accepts an array as a second parameter. This parameter is used as a condition on when to perform the passed function. So, let’s say you want to change a counter only after the variable <strong><strong>counter </strong></strong>changes, you can do it like so:</p><pre><code class=\"language-JS\">useEffect(() =&gt; document.title = `You have clicked ${counter} times`, [counter]);</code></pre><p>This way, the function passed to <code>useEffect</code> will run after render only if the value for <code>counter</code><strong><strong> </strong></strong>changes.</p><p>If we want the function to run only after the first render, we can do that by passing an <strong><strong>empty</strong></strong> array as the second parameter.</p><p>Let’s come back now to what we want to do. We want to show a welcome message when the user first opens the page, then change that message after 3 seconds. We can do that by adding the following inside <strong><strong>App.js</strong></strong>:</p><pre><code class=\"language-JS\">import React, {useEffect} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n   useEffect(() =&gt; {\n     setTimeout(() =&gt; {\n       let welcomeMessage = document.getElementById(\"welcomeMessage\");\n       welcomeMessage.innerHTML = \"Try Out Our Trivia Generator!\";\n     }, 3000);\n   }, []);\n   return (\n     &lt;div className=\"App\"&gt;\n       &lt;header className=\"App-header\"&gt;\n         &lt;h1 id=\"welcomeMessage\"&gt;Welcome to Numbers Trivia!&lt;/h1&gt;\n         &lt;Form /&gt;\n       &lt;/header&gt;\n     &lt;/div&gt;\n   ); }  \nexport default App;</code></pre><p>Here’s what we’re doing:</p><ol><li><strong><strong>Line 1:</strong></strong> We added an import for <code>useEffect</code></li><li><strong><strong>Line 4: </strong></strong>We changed our class component into a function component</li><li><strong><strong>Line 5–10: </strong></strong>we added an effect to our function component. This effect sets a timer after 3 seconds that will change the text in the element with the id <code>welcomeMessage</code><strong><strong>. </strong></strong>Because we passed an <strong><strong>empty</strong></strong> array to <code>useEffect</code>, this effect will only run once.</li><li><strong><strong>Line 11–17: </strong></strong>We replaced the previous code in <strong><strong>App.js </strong></strong>to render an <strong><strong>h1 </strong></strong>element having the id <code>welcomeMessage</code><strong><strong>, </strong></strong>which is our target element.</li></ol><p>Okay, now go to our web page and see the changes. At first, the welcome message “<strong><strong>Welcome to Numbers Trivia!</strong></strong>” will show up, then 3 seconds later it will change into “<strong><strong>Try Out Our Trivia Generator!</strong></strong>” We just used a React Hook!</p><p>Next, let’s create our form input elements. To do that, we will create a new React component called <code>Form</code><strong><strong>. </strong></strong>Create in the directory <strong><strong>components</strong></strong> the file <strong><strong>Form.js. </strong></strong>For now, it will just include the following:</p><pre><code class=\"language-JS\">import React from 'react';  \nfunction Form(props){\n}\nexport default Form;</code></pre><p>This will create the new React component. We’re just importing React, then we’re creating a function called Form. As we said earlier in the tutorial, with the use of hooks we can now create components as stateful functions rather than classes. And in the last line, we’re exporting <strong><strong>Form</strong></strong> in order to import it in other files.</p><p>In the form, we will have a <strong><strong>text </strong></strong>input and <strong><strong>select </strong></strong>elements. This is based on the API we’re using. In the API, two parameters can be sent:</p><ol><li><strong><strong>number: </strong></strong>the number you want to get the trivia for. It can be an <strong><strong>integer</strong></strong>, a date of the form <strong><strong>month/day, </strong></strong>or the keyword <strong><strong>random </strong></strong>which will retrieve facts about a random number.</li><li><strong><strong>type: </strong></strong>the type of information you want to get. There are a few types: <strong><strong>math, date, year, </strong></strong>or, the default, <strong><strong>trivia.</strong></strong></li></ol><p>We will consider the text input element as optional. If the user does not enter a number or a date, we will send the keyword <strong><strong>random</strong></strong> for the number element.</p><p>Let’s add the following code inside the <strong><strong>Form</strong></strong> function in order to render our form:</p><pre><code class=\"language-JS\">function Form(props){\n  return (&lt;form&gt;\n             &lt;div&gt;\n              &lt;input type=\"text\" name=\"number\" placeholder=\"Enter a number (Optional)\" /&gt;\n             &lt;/div&gt;\n             &lt;div&gt;\n              &lt;select name=\"type\"&gt;\n               &lt;option value=\"trivia\"&gt;Trivia&lt;/option&gt;\n               &lt;option value=\"math\"&gt;Math&lt;/option&gt;\n               &lt;option value=\"date\"&gt;Date&lt;/option&gt;\n               &lt;option value=\"year\"&gt;Year&lt;/option&gt;\n              &lt;/select&gt;\n             &lt;/div&gt;\n             &lt;button type=\"submit\"&gt;Generate&lt;/button&gt;\n            &lt;/form&gt;); \n}</code></pre><p>This will create the form with the <strong><strong>text </strong></strong>input and <strong><strong>select </strong></strong>and <strong><strong>button </strong></strong>elements.</p><p>After that, we need to import and render the <strong><strong>Form</strong></strong> component in our <strong><strong>App </strong></strong>component:</p><pre><code class=\"language-JS\">import React, {useEffect} from 'react';\nimport Form from './Form';\nimport '../styles/App.css';  \nfunction App() {\n   useEffect(() =&gt; {\n     setTimeout(() =&gt; {\n       let welcomeMessage = document.getElementById(\"welcomeMessage\");\n       welcomeMessage.innerHTML = \"Try Out Our Trivia Generator!\";\n     }, 3000);\n   }, []);\n   return (\n     &lt;div className=\"App\"&gt;\n       &lt;header className=\"App-header\"&gt;\n         &lt;h1 id=\"welcomeMessage\"&gt;Welcome to Numbers Trivia!&lt;/h1&gt;\n         &lt;Form /&gt;\n       &lt;/header&gt;\n     &lt;/div&gt;\n   );\n }\nexport default App;</code></pre><p>We have changed the imports to import our <code>Form</code><strong><strong> </strong></strong>component, and we added <code>&lt;Form /&gt;</code><strong><strong> </strong></strong>to render the form.</p><p>Let’s also add more styles just to make our form look a little better. Add the following at the end of <strong><strong>App.css</strong></strong>:</p><pre><code class=\"language-CSS\">form {\n   font-size: 15px;\n}  \nform input, form select {\n   padding: 5px;\n}  \nform select {\n   width: 100%; \n}  \nform div {\n   margin-bottom: 8px;\n}</code></pre><p>If you refresh the page now, you will find it has changed and now it’s showing our form.</p><p>Now, we need to add some logic to our form. <strong><strong>On Submit</strong></strong>, we need to get the values of our input elements, then call the API to retrieve the results.</p><p>To handle form elements and their values, you need to use the state of the component. You make the value of the element equal to a property in the state of the component.</p><p>Before hooks, in order to get the value in the state you would have to use <code>this.state.value</code><strong><strong>, </strong></strong>and then to set the state, you will need to call <code>this.setState</code>.</p><p>Now, you can use the state hook. The state hook is the <code>useState</code><strong><strong> </strong></strong>function. It accepts one argument, which is the initial value, and it returns a pair of values: the <strong><strong>current state</strong></strong> and a <strong><strong>function</strong></strong> that updates it. Then, you will be able to access the current state using the first returned value, and update it using the second returned value which is the function.</p><p>Here’s an example:</p><pre><code class=\"language-JS\">const [count, setCount] = useState(0);</code></pre><p>in this example, we call the <code>useState</code><strong><strong> </strong></strong>hook and pass it 0, and we set the returned value equal to <code>count</code> and <code>setCount</code>. This means that we have created state variable called <code>count</code>. Its initial value is 0, and to change its value we can use <code>setCount</code>.</p><p>For our <code>Form</code><strong><strong> </strong></strong>component, we need two state variables, one for the text<strong><strong> </strong></strong>input which we will call <code>number</code>, and one for the select<strong><strong> </strong></strong>input which we will call <code>type</code>. Then, on change event for these two input elements, we will change the values for <code>number</code><strong><strong> </strong></strong>and <code>type</code> using the function returned by <code>setState</code><strong><strong>.</strong></strong></p><p>Open our <code>Form</code><strong><strong> </strong></strong>component and change it to the following:</p><pre><code class=\"language-JS\">import React, { useState } from 'react';\nfunction Form(props){\n  let [number, setNumber] = useState(\"random\");\n  let [type, setType] = useState(\"trivia\");\n  function onNumberChanged(e){\n    let value = e.target.value.trim();\n    if(!value.length){\n      setNumber(\"random\"); //default value\n    } else {\n      setNumber(value);\n    }\n  }\n  function onTypeChanged(e){\n    let value = e.target.value.trim();\n    if(!value.length){\n      setType(\"trivia\"); //default value\n    } else {\n      setType(value);\n    }\n  }\n  return (&lt;form&gt;\n            &lt;div&gt;\n              &lt;input type=\"text\" name=\"number\" placeholder=\"Enter a number (Optional)\" value={number} onChange={onNumberChanged} /&gt;\n            &lt;/div&gt;\n            &lt;div&gt;\n              &lt;select name=\"type\" value={type} onChange={onTypeChanged}&gt;\n                &lt;option value=\"trivia\"&gt;Trivia&lt;/option&gt;\n                &lt;option value=\"math\"&gt;Math&lt;/option&gt;\n                &lt;option value=\"date\"&gt;Date&lt;/option&gt;\n                &lt;option value=\"year\"&gt;Year&lt;/option&gt;\n              &lt;/select&gt;\n            &lt;/div&gt;\n            &lt;button type=\"submit\"&gt;Generate&lt;/button&gt;\n&lt;/form&gt;);\n}\nexport default Form;</code></pre><ol><li><strong><strong>Line 1: </strong></strong>add an import for <code>useState</code> hook.</li><li><strong><strong>Line 3–4: </strong></strong>create two state variables <code>number</code> and <code>type</code> using <code>useState</code> . Here we pass <strong><strong>random </strong></strong>as the initial value for number, and <strong><strong>trivia </strong></strong>as initial value for type because they are the default values for the parameters in the API.</li><li><strong><strong>Line 5–10: </strong></strong>implement input change handler functions for both text and select inputs, where we change the value of the state variables using the functions returned by <code>useState</code> . If the value is unset, we automatically change the values to the default value.</li><li><strong><strong>Line 13: </strong></strong>pass the <code>onNumberChanged</code> function to <code>onChange</code> event for text input.</li><li><strong><strong>Line 16: </strong></strong>pass the <code>onTypeChanged</code> function to <code>onChange</code> event for select input.</li></ol><p>In addition, let’s go back to our <code>App</code> component to modify it and use states. Instead of modifying our welcome message by changing the <code>innerHTML</code> of the element, we will use a state. Our App component should now be like this:</p><pre><code>import React, {useEffect, useState} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n  const [ welcomeMessage, setWelcomeMessage ] = useState(\n    \"Welcome to Numbers Trivia!\",\n  );\nuseEffect(() =&gt; {\n    setTimeout(() =&gt; {\n      setWelcomeMessage(\"Try Out Our Trivia Generator!\");\n    }, 3000);\n  }, []);\nreturn (\n    &lt;div className=\"App\"&gt;\n      &lt;header className=\"App-header\"&gt;\n        &lt;h1&gt;{welcomeMessage}&lt;/h1&gt;\n      &lt;/header&gt;\n      &lt;Form/&gt;\n    &lt;/div&gt;\n  );\n}\nexport default App;</code></pre><p>Now, we are using <code>useState</code> to declare and initialize our welcome message. It will return <code>welcomeMessage</code> , our state variable, and <code>setWelcomeMessage</code> , which we will use to change the value of <code>welcomeMessage</code> after 3 seconds from “<strong><strong>Welcome to Numbers Trivia!</strong></strong>” to “<strong><strong>Try Out Our Trivia Generator!</strong></strong>”</p><p>What’s left now is to add a function to handle the form’s <code>onSubmit</code> event. On submit, we will send a request to the API with our parameters, then display the result.</p><p>In order to perform the request, we need to install <a href=\"https://github.com/axios/axios\" rel=\"noopener nofollow\">axios</a>:</p><pre><code class=\"language-Shell\">npm i axios</code></pre><p>Then, require axios at the beginning of <strong><strong>Form.js:</strong></strong></p><pre><code class=\"language-JS\">const axios = require('axios');</code></pre><p>Now, add the following function below <code>onTypeChanged</code> in our <strong><strong>Form</strong></strong> component:</p><pre><code class=\"language-JS\">function onSubmit(e){\n  e.preventDefault();\n  axios.get('http://numbersapi.com/' + number + '/' + type)\n       .then(function(response){\n         let elm = document.getElementById('result');\n         elm.innerHTML = response.data;\n       }).catch(function(e){\n         console.log(\"error\", e); //simple error handling\n       });\n}</code></pre><p>We’re just performing a request to the API, passing the <code>number</code> and <code>type</code> then displaying the result in an element of id <code>result</code> (which we will add in a minute). In case of an error, we’re just displaying it in the console just as a simple error handling.</p><p>Now, let’s add this function as the handler for the form <code>onSubmit</code> event in the return statement in Form.js:</p><pre><code class=\"language-JSX\">&lt;form onSubmit={onSubmit}&gt;</code></pre><p>The only thing left is to add the <code>#result</code> element. We can add it in <strong><strong>App.js </strong></strong>before <code>&lt;Form /&gt;</code> :</p><pre><code class=\"language-JSX\">&lt;div id=\"result\" style={{marginBottom: '15px'}}&gt;&lt;/div&gt;</code></pre><p>Alright, now go to your website and discover all new trivia about numbers!</p><hr><h2 id=\"conclusion\">Conclusion</h2><p>You just created a React app and used some React Hooks! Of course, there’s still more to explore and learn, so be sure to head to the <a href=\"https://reactjs.org/docs/hooks-intro.html\" rel=\"noopener nofollow\">docs</a> to learn more about React Hooks.</p>","url":"https://backend.shahednasser.com/react-hooks-tutorial-create-a-number-trivia-generator-website/","canonical_url":null,"uuid":"033786bf-592f-454b-b640-42920b676fb8","codeinjection_foot":null,"codeinjection_head":null,"codeinjection_styles":null,"comment_id":"5faa42902280bc001e2ccc95","reading_time":11,"send_email_when_published":null,"email_subject":null,"childHtmlRehype":{"html":"<p>Hooks have been officially added to React as of React 16.8. One of the main benefits of Hooks in React is that you can use state and effect (which is generally a combination of different life cycles into one) in a component without creating a class.</p><p>In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that gives the user some options to pick from in order to generate some random number trivia.</p><p>You can check out the demo for the website <a href=\"http://numbers-trivia.surge.sh/\" rel=\"noopener nofollow\">here</a>, and the source code on the <a href=\"https://github.com/shahednasser/numbers-trivia\" rel=\"noopener nofollow\">GitHub repository</a>.</p><p>Let’s first start by creating a react app. Since our website will be very simple, we will use the <code class=\"language-text\">create-react-app</code> command. If you don’t have it installed, you can install it using <code class=\"language-text\">npm</code><strong><strong>.</strong></strong></p><p>Run the following in your terminal or CMD:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"shell\"><pre class=\"language-shell\"><code class=\"language-shell\"><span class=\"token function\">npm</span> i -g create-react-app</code></pre></div><p>This will install <code class=\"language-text\">create-react-app</code> globally.</p><p>Now we can create our React app:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"shell\"><pre class=\"language-shell\"><code class=\"language-shell\">create-react-app numbers-trivia</code></pre></div><p>Running this command will create a directory in the working directory with the name you supply for the React app. I named it <strong><strong>numbers-trivia</strong></strong> but you can call it whatever you want.</p><p>Inside that directory, it will also install all the packages and files needed to run the website. It will install packages like <strong><strong>react</strong></strong>, <strong><strong>react-dom</strong></strong>, <strong><strong>react-scripts</strong></strong> and more.</p><p>Once it’s done, change into the newly created directory and start the server:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"shell\"><pre class=\"language-shell\"><code class=\"language-shell\"><span class=\"token builtin class-name\">cd</span> numbers-trivia\n<span class=\"token function\">npm</span> start</code></pre></div><p>Once you start the server, a web page of your website in your favorite browser will open. You will see a page with just the logo and a link to learn React.</p><p>Before we start changing the page, if you are not familiar with React, let’s take a look at the structure of our React app. It should look something like this:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_R1irPlPj9UsboCM_KI5CgA.png\" class=\"kg-image\" alt=\"\" loading=\"lazy\"></figure><p>In our root directory, we will find a bunch of directories. <strong><strong>node_modules </strong></strong>holds all the packages React needs to run and any package you might add. <strong><strong>public </strong></strong>holds the files our server serves.</p><p>The directory that we will spend most of our time in is the <strong><strong>src</strong></strong> directory. This directory will hold all of our React components.</p><p>As you can see there are a bunch of files in that directory. <strong><strong>index.js</strong></strong> is basically the file that renders our highest React component.</p><p>We only have one React component right now which is in <strong><strong>App.js. </strong></strong>If you open it, you will find the code that renders the logo with the link to learn React that you currently see on the website.</p><p>So, in order to see how changing our App component will change the content of the website, let’s modify the code by removing the current content and replacing it with our favorite phrase: “Hello, World!”</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> Component <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span> \n<span class=\"token keyword\">import</span> logo <span class=\"token keyword\">from</span> <span class=\"token string\">'./logo.svg'</span> \n<span class=\"token keyword\">import</span> <span class=\"token string\">'./App.css'</span>  \n<span class=\"token keyword\">class</span> <span class=\"token class-name\">App</span> <span class=\"token keyword\">extends</span> <span class=\"token class-name\">Component</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token function\">render</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n       <span class=\"token operator\">&#x3C;</span>div className<span class=\"token operator\">=</span><span class=\"token string\">\"App\"</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>header className<span class=\"token operator\">=</span><span class=\"token string\">\"App-header\"</span><span class=\"token operator\">></span>\n           <span class=\"token operator\">&#x3C;</span>h1<span class=\"token operator\">></span>Hello<span class=\"token punctuation\">,</span> World<span class=\"token operator\">!</span><span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>h1<span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>header<span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n     <span class=\"token punctuation\">)</span>\n   <span class=\"token punctuation\">}</span>\n <span class=\"token punctuation\">}</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> App</code></pre></div><p>We just replaced the content of the <strong><strong>header</strong></strong> element. Now, if your server is still running you will see that your page updated without you refreshing it, and you will see that the previous content is replaced with <strong><strong>Hello, World!</strong></strong></p><p>So now we know how and where we should edit our React components in order to get the result we want. We can go ahead and start with our objective.</p><p>What we’ll do for this website is the following:</p><ol><li>Show a welcome message the first time the user opens the website, then replace it with a message prompting the user to try the generator.</li><li>Render a form with <strong><strong>text </strong></strong>and <strong><strong>select</strong></strong> inputs. The <strong><strong>text </strong></strong>input is where the user can enter the number they want to see trivia about, and the <strong><strong>select </strong></strong>input will provide the user with options related to the trivia.</li><li>On submitting the form, send a request to <a href=\"http://numbersapi.com/\" rel=\"noopener nofollow\">this API</a> to fetch the trivia we need.</li><li>Render the trivia for the user to see it.</li></ol><p>Let’s start by organizing our directory structure first. In React it’s good practice to create a directory inside <strong><strong>src</strong></strong> holding all the components. We’ll create a directory called <strong><strong>components</strong></strong>. Once you create the directory, move <strong><strong>App.js</strong></strong> into there. We will also create a directory called <strong><strong>styles</strong></strong> and move <strong><strong>App.css </strong></strong>and <strong><strong>index.css </strong></strong>into it.</p><p>When you do that, you will need to change the imports in your files as following:</p><ol><li>in <strong><strong>index.js:</strong></strong></li></ol><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> ReactDOM <span class=\"token keyword\">from</span> <span class=\"token string\">'react-dom'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> <span class=\"token string\">'../styles/index.css'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> App <span class=\"token keyword\">from</span> <span class=\"token string\">'./components/App'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span>  <span class=\"token keyword\">as</span> serviceWorker <span class=\"token keyword\">from</span> <span class=\"token string\">'./serviceWorker'</span><span class=\"token punctuation\">;</span></code></pre></div><p>2. in <strong><strong>App.js:</strong></strong></p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> Component <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> logo <span class=\"token keyword\">from</span> <span class=\"token string\">'./logo.svg'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> <span class=\"token string\">'../styles/App.css'</span><span class=\"token punctuation\">;</span></code></pre></div><p>Our directory structure should look like this now:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_Aqgelb3qbhJiESUbGGNUoQ.png\" class=\"kg-image\" alt=\"\" loading=\"lazy\"></figure><p>We will go ahead now and start building our webpage.</p><p>The first thing in our objectives list is showing a welcome message when the user first opens the webpage. It will show up for 3 seconds, and then changes to another message that will prompt the user to try out the trivia generator.</p><p>Without hooks, this could be done by using React’s lifecycle method <code class=\"language-text\">componentDidMount</code><em><em> </em></em>which runs right after the component first renders.</p><p>Now, we can use the <a href=\"https://reactjs.org/docs/hooks-effect.html\" rel=\"noopener nofollow\"><em><em>effect hook</em></em></a><em><em> </em></em>instead. It will look something like this:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">//perform something post render</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div><p>The function you pass to <code class=\"language-text\">useEffect</code> will be executed after every render. This combines the lifecycles methods <code class=\"language-text\">componentDidMount</code><strong><strong> </strong></strong>and <code class=\"language-text\">componentDidUpdate</code> into one.</p><p>What if you want to do something just after the first time the component renders, like in <code class=\"language-text\">componentDidMount</code>? You can do this by passing a second parameter to <code class=\"language-text\">useEffect</code>.</p><p><code class=\"language-text\">useEffect</code><strong><strong> </strong></strong>accepts an array as a second parameter. This parameter is used as a condition on when to perform the passed function. So, let’s say you want to change a counter only after the variable <strong><strong>counter </strong></strong>changes, you can do it like so:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> document<span class=\"token punctuation\">.</span>title <span class=\"token operator\">=</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">You have clicked </span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>counter<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token string\"> times</span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span>counter<span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div><p>This way, the function passed to <code class=\"language-text\">useEffect</code> will run after render only if the value for <code class=\"language-text\">counter</code><strong><strong> </strong></strong>changes.</p><p>If we want the function to run only after the first render, we can do that by passing an <strong><strong>empty</strong></strong> array as the second parameter.</p><p>Let’s come back now to what we want to do. We want to show a welcome message when the user first opens the page, then change that message after 3 seconds. We can do that by adding the following inside <strong><strong>App.js</strong></strong>:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>useEffect<span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> Form <span class=\"token keyword\">from</span> <span class=\"token string\">'./Form'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> <span class=\"token string\">'../styles/App.css'</span><span class=\"token punctuation\">;</span> \n \n<span class=\"token keyword\">function</span> <span class=\"token function\">App</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token function\">setTimeout</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">let</span> welcomeMessage <span class=\"token operator\">=</span> document<span class=\"token punctuation\">.</span><span class=\"token function\">getElementById</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"welcomeMessage\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       welcomeMessage<span class=\"token punctuation\">.</span>innerHTML <span class=\"token operator\">=</span> <span class=\"token string\">\"Try Out Our Trivia Generator!\"</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token number\">3000</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n     <span class=\"token operator\">&#x3C;</span>div className<span class=\"token operator\">=</span><span class=\"token string\">\"App\"</span><span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span>header className<span class=\"token operator\">=</span><span class=\"token string\">\"App-header\"</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>h1 id<span class=\"token operator\">=</span><span class=\"token string\">\"welcomeMessage\"</span><span class=\"token operator\">></span>Welcome to Numbers Trivia<span class=\"token operator\">!</span><span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>h1<span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>Form <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>header<span class=\"token operator\">></span>\n     <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n   <span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token punctuation\">}</span>  \n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> App<span class=\"token punctuation\">;</span></code></pre></div><p>Here’s what we’re doing:</p><ol><li><strong><strong>Line 1:</strong></strong> We added an import for <code class=\"language-text\">useEffect</code></li><li><strong><strong>Line 4: </strong></strong>We changed our class component into a function component</li><li><strong><strong>Line 5–10: </strong></strong>we added an effect to our function component. This effect sets a timer after 3 seconds that will change the text in the element with the id <code class=\"language-text\">welcomeMessage</code><strong><strong>. </strong></strong>Because we passed an <strong><strong>empty</strong></strong> array to <code class=\"language-text\">useEffect</code>, this effect will only run once.</li><li><strong><strong>Line 11–17: </strong></strong>We replaced the previous code in <strong><strong>App.js </strong></strong>to render an <strong><strong>h1 </strong></strong>element having the id <code class=\"language-text\">welcomeMessage</code><strong><strong>, </strong></strong>which is our target element.</li></ol><p>Okay, now go to our web page and see the changes. At first, the welcome message “<strong><strong>Welcome to Numbers Trivia!</strong></strong>” will show up, then 3 seconds later it will change into “<strong><strong>Try Out Our Trivia Generator!</strong></strong>” We just used a React Hook!</p><p>Next, let’s create our form input elements. To do that, we will create a new React component called <code class=\"language-text\">Form</code><strong><strong>. </strong></strong>Create in the directory <strong><strong>components</strong></strong> the file <strong><strong>Form.js. </strong></strong>For now, it will just include the following:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span>  \n<span class=\"token keyword\">function</span> <span class=\"token function\">Form</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">props</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n<span class=\"token punctuation\">}</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> Form<span class=\"token punctuation\">;</span></code></pre></div><p>This will create the new React component. We’re just importing React, then we’re creating a function called Form. As we said earlier in the tutorial, with the use of hooks we can now create components as stateful functions rather than classes. And in the last line, we’re exporting <strong><strong>Form</strong></strong> in order to import it in other files.</p><p>In the form, we will have a <strong><strong>text </strong></strong>input and <strong><strong>select </strong></strong>elements. This is based on the API we’re using. In the API, two parameters can be sent:</p><ol><li><strong><strong>number: </strong></strong>the number you want to get the trivia for. It can be an <strong><strong>integer</strong></strong>, a date of the form <strong><strong>month/day, </strong></strong>or the keyword <strong><strong>random </strong></strong>which will retrieve facts about a random number.</li><li><strong><strong>type: </strong></strong>the type of information you want to get. There are a few types: <strong><strong>math, date, year, </strong></strong>or, the default, <strong><strong>trivia.</strong></strong></li></ol><p>We will consider the text input element as optional. If the user does not enter a number or a date, we will send the keyword <strong><strong>random</strong></strong> for the number element.</p><p>Let’s add the following code inside the <strong><strong>Form</strong></strong> function in order to render our form:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">Form</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">props</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">&#x3C;</span>form<span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span>div<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span>input type<span class=\"token operator\">=</span><span class=\"token string\">\"text\"</span> name<span class=\"token operator\">=</span><span class=\"token string\">\"number\"</span> placeholder<span class=\"token operator\">=</span><span class=\"token string\">\"Enter a number (Optional)\"</span> <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span>div<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span>select name<span class=\"token operator\">=</span><span class=\"token string\">\"type\"</span><span class=\"token operator\">></span>\n               <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"trivia\"</span><span class=\"token operator\">></span>Trivia<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n               <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"math\"</span><span class=\"token operator\">></span>Math<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n               <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"date\"</span><span class=\"token operator\">></span>Date<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n               <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"year\"</span><span class=\"token operator\">></span>Year<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>select<span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span>button type<span class=\"token operator\">=</span><span class=\"token string\">\"submit\"</span><span class=\"token operator\">></span>Generate<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>button<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>form<span class=\"token operator\">></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> \n<span class=\"token punctuation\">}</span></code></pre></div><p>This will create the form with the <strong><strong>text </strong></strong>input and <strong><strong>select </strong></strong>and <strong><strong>button </strong></strong>elements.</p><p>After that, we need to import and render the <strong><strong>Form</strong></strong> component in our <strong><strong>App </strong></strong>component:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>useEffect<span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> Form <span class=\"token keyword\">from</span> <span class=\"token string\">'./Form'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> <span class=\"token string\">'../styles/App.css'</span><span class=\"token punctuation\">;</span>  \n<span class=\"token keyword\">function</span> <span class=\"token function\">App</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token function\">setTimeout</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">let</span> welcomeMessage <span class=\"token operator\">=</span> document<span class=\"token punctuation\">.</span><span class=\"token function\">getElementById</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"welcomeMessage\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       welcomeMessage<span class=\"token punctuation\">.</span>innerHTML <span class=\"token operator\">=</span> <span class=\"token string\">\"Try Out Our Trivia Generator!\"</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token number\">3000</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n     <span class=\"token operator\">&#x3C;</span>div className<span class=\"token operator\">=</span><span class=\"token string\">\"App\"</span><span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span>header className<span class=\"token operator\">=</span><span class=\"token string\">\"App-header\"</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>h1 id<span class=\"token operator\">=</span><span class=\"token string\">\"welcomeMessage\"</span><span class=\"token operator\">></span>Welcome to Numbers Trivia<span class=\"token operator\">!</span><span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>h1<span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>Form <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>header<span class=\"token operator\">></span>\n     <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n   <span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n <span class=\"token punctuation\">}</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> App<span class=\"token punctuation\">;</span></code></pre></div><p>We have changed the imports to import our <code class=\"language-text\">Form</code><strong><strong> </strong></strong>component, and we added <code class=\"language-text\">&#x3C;Form /></code><strong><strong> </strong></strong>to render the form.</p><p>Let’s also add more styles just to make our form look a little better. Add the following at the end of <strong><strong>App.css</strong></strong>:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">form</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token property\">font-size</span><span class=\"token punctuation\">:</span> 15px<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>  \n<span class=\"token selector\">form input, form select</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token property\">padding</span><span class=\"token punctuation\">:</span> 5px<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>  \n<span class=\"token selector\">form select</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token property\">width</span><span class=\"token punctuation\">:</span> 100%<span class=\"token punctuation\">;</span> \n<span class=\"token punctuation\">}</span>  \n<span class=\"token selector\">form div</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token property\">margin-bottom</span><span class=\"token punctuation\">:</span> 8px<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>If you refresh the page now, you will find it has changed and now it’s showing our form.</p><p>Now, we need to add some logic to our form. <strong><strong>On Submit</strong></strong>, we need to get the values of our input elements, then call the API to retrieve the results.</p><p>To handle form elements and their values, you need to use the state of the component. You make the value of the element equal to a property in the state of the component.</p><p>Before hooks, in order to get the value in the state you would have to use <code class=\"language-text\">this.state.value</code><strong><strong>, </strong></strong>and then to set the state, you will need to call <code class=\"language-text\">this.setState</code>.</p><p>Now, you can use the state hook. The state hook is the <code class=\"language-text\">useState</code><strong><strong> </strong></strong>function. It accepts one argument, which is the initial value, and it returns a pair of values: the <strong><strong>current state</strong></strong> and a <strong><strong>function</strong></strong> that updates it. Then, you will be able to access the current state using the first returned value, and update it using the second returned value which is the function.</p><p>Here’s an example:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">const</span> <span class=\"token punctuation\">[</span>count<span class=\"token punctuation\">,</span> setCount<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token number\">0</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div><p>in this example, we call the <code class=\"language-text\">useState</code><strong><strong> </strong></strong>hook and pass it 0, and we set the returned value equal to <code class=\"language-text\">count</code> and <code class=\"language-text\">setCount</code>. This means that we have created state variable called <code class=\"language-text\">count</code>. Its initial value is 0, and to change its value we can use <code class=\"language-text\">setCount</code>.</p><p>For our <code class=\"language-text\">Form</code><strong><strong> </strong></strong>component, we need two state variables, one for the text<strong><strong> </strong></strong>input which we will call <code class=\"language-text\">number</code>, and one for the select<strong><strong> </strong></strong>input which we will call <code class=\"language-text\">type</code>. Then, on change event for these two input elements, we will change the values for <code class=\"language-text\">number</code><strong><strong> </strong></strong>and <code class=\"language-text\">type</code> using the function returned by <code class=\"language-text\">setState</code><strong><strong>.</strong></strong></p><p>Open our <code class=\"language-text\">Form</code><strong><strong> </strong></strong>component and change it to the following:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> useState <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">function</span> <span class=\"token function\">Form</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">props</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">let</span> <span class=\"token punctuation\">[</span>number<span class=\"token punctuation\">,</span> setNumber<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"random\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token keyword\">let</span> <span class=\"token punctuation\">[</span>type<span class=\"token punctuation\">,</span> setType<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"trivia\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token keyword\">function</span> <span class=\"token function\">onNumberChanged</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">e</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">let</span> value <span class=\"token operator\">=</span> e<span class=\"token punctuation\">.</span>target<span class=\"token punctuation\">.</span>value<span class=\"token punctuation\">.</span><span class=\"token function\">trim</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token keyword\">if</span><span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>value<span class=\"token punctuation\">.</span>length<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setNumber</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"random\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">//default value</span>\n    <span class=\"token punctuation\">}</span> <span class=\"token keyword\">else</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setNumber</span><span class=\"token punctuation\">(</span>value<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword\">function</span> <span class=\"token function\">onTypeChanged</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">e</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">let</span> value <span class=\"token operator\">=</span> e<span class=\"token punctuation\">.</span>target<span class=\"token punctuation\">.</span>value<span class=\"token punctuation\">.</span><span class=\"token function\">trim</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token keyword\">if</span><span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>value<span class=\"token punctuation\">.</span>length<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setType</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"trivia\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">//default value</span>\n    <span class=\"token punctuation\">}</span> <span class=\"token keyword\">else</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setType</span><span class=\"token punctuation\">(</span>value<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">&#x3C;</span>form<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span>div<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span>input type<span class=\"token operator\">=</span><span class=\"token string\">\"text\"</span> name<span class=\"token operator\">=</span><span class=\"token string\">\"number\"</span> placeholder<span class=\"token operator\">=</span><span class=\"token string\">\"Enter a number (Optional)\"</span> value<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>number<span class=\"token punctuation\">}</span> onChange<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>onNumberChanged<span class=\"token punctuation\">}</span> <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span>div<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span>select name<span class=\"token operator\">=</span><span class=\"token string\">\"type\"</span> value<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>type<span class=\"token punctuation\">}</span> onChange<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>onTypeChanged<span class=\"token punctuation\">}</span><span class=\"token operator\">></span>\n                <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"trivia\"</span><span class=\"token operator\">></span>Trivia<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n                <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"math\"</span><span class=\"token operator\">></span>Math<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n                <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"date\"</span><span class=\"token operator\">></span>Date<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n                <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"year\"</span><span class=\"token operator\">></span>Year<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>select<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span>button type<span class=\"token operator\">=</span><span class=\"token string\">\"submit\"</span><span class=\"token operator\">></span>Generate<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>button<span class=\"token operator\">></span>\n<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>form<span class=\"token operator\">></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> Form<span class=\"token punctuation\">;</span></code></pre></div><ol><li><strong><strong>Line 1: </strong></strong>add an import for <code class=\"language-text\">useState</code> hook.</li><li><strong><strong>Line 3–4: </strong></strong>create two state variables <code class=\"language-text\">number</code> and <code class=\"language-text\">type</code> using <code class=\"language-text\">useState</code> . Here we pass <strong><strong>random </strong></strong>as the initial value for number, and <strong><strong>trivia </strong></strong>as initial value for type because they are the default values for the parameters in the API.</li><li><strong><strong>Line 5–10: </strong></strong>implement input change handler functions for both text and select inputs, where we change the value of the state variables using the functions returned by <code class=\"language-text\">useState</code> . If the value is unset, we automatically change the values to the default value.</li><li><strong><strong>Line 13: </strong></strong>pass the <code class=\"language-text\">onNumberChanged</code> function to <code class=\"language-text\">onChange</code> event for text input.</li><li><strong><strong>Line 16: </strong></strong>pass the <code class=\"language-text\">onTypeChanged</code> function to <code class=\"language-text\">onChange</code> event for select input.</li></ol><p>In addition, let’s go back to our <code class=\"language-text\">App</code> component to modify it and use states. Instead of modifying our welcome message by changing the <code class=\"language-text\">innerHTML</code> of the element, we will use a state. Our App component should now be like this:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">import React, {useEffect, useState} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n  const [ welcomeMessage, setWelcomeMessage ] = useState(\n    \"Welcome to Numbers Trivia!\",\n  );\nuseEffect(() => {\n    setTimeout(() => {\n      setWelcomeMessage(\"Try Out Our Trivia Generator!\");\n    }, 3000);\n  }, []);\nreturn (\n    &#x3C;div className=\"App\">\n      &#x3C;header className=\"App-header\">\n        &#x3C;h1>{welcomeMessage}&#x3C;/h1>\n      &#x3C;/header>\n      &#x3C;Form/>\n    &#x3C;/div>\n  );\n}\nexport default App;</code></pre></div><p>Now, we are using <code class=\"language-text\">useState</code> to declare and initialize our welcome message. It will return <code class=\"language-text\">welcomeMessage</code> , our state variable, and <code class=\"language-text\">setWelcomeMessage</code> , which we will use to change the value of <code class=\"language-text\">welcomeMessage</code> after 3 seconds from “<strong><strong>Welcome to Numbers Trivia!</strong></strong>” to “<strong><strong>Try Out Our Trivia Generator!</strong></strong>”</p><p>What’s left now is to add a function to handle the form’s <code class=\"language-text\">onSubmit</code> event. On submit, we will send a request to the API with our parameters, then display the result.</p><p>In order to perform the request, we need to install <a href=\"https://github.com/axios/axios\" rel=\"noopener nofollow\">axios</a>:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"shell\"><pre class=\"language-shell\"><code class=\"language-shell\"><span class=\"token function\">npm</span> i axios</code></pre></div><p>Then, require axios at the beginning of <strong><strong>Form.js:</strong></strong></p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">const</span> axios <span class=\"token operator\">=</span> <span class=\"token function\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'axios'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div><p>Now, add the following function below <code class=\"language-text\">onTypeChanged</code> in our <strong><strong>Form</strong></strong> component:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">onSubmit</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">e</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n  e<span class=\"token punctuation\">.</span><span class=\"token function\">preventDefault</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  axios<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'http://numbersapi.com/'</span> <span class=\"token operator\">+</span> number <span class=\"token operator\">+</span> <span class=\"token string\">'/'</span> <span class=\"token operator\">+</span> type<span class=\"token punctuation\">)</span>\n       <span class=\"token punctuation\">.</span><span class=\"token function\">then</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">function</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">response</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n         <span class=\"token keyword\">let</span> elm <span class=\"token operator\">=</span> document<span class=\"token punctuation\">.</span><span class=\"token function\">getElementById</span><span class=\"token punctuation\">(</span><span class=\"token string\">'result'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         elm<span class=\"token punctuation\">.</span>innerHTML <span class=\"token operator\">=</span> response<span class=\"token punctuation\">.</span>data<span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">catch</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">function</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">e</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n         console<span class=\"token punctuation\">.</span><span class=\"token function\">log</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"error\"</span><span class=\"token punctuation\">,</span> e<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">//simple error handling</span>\n       <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>We’re just performing a request to the API, passing the <code class=\"language-text\">number</code> and <code class=\"language-text\">type</code> then displaying the result in an element of id <code class=\"language-text\">result</code> (which we will add in a minute). In case of an error, we’re just displaying it in the console just as a simple error handling.</p><p>Now, let’s add this function as the handler for the form <code class=\"language-text\">onSubmit</code> event in the return statement in Form.js:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"jsx\"><pre class=\"language-jsx\"><code class=\"language-jsx\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;</span>form</span> <span class=\"token attr-name\">onSubmit</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>onSubmit<span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span></code></pre></div><p>The only thing left is to add the <code class=\"language-text\">#result</code> element. We can add it in <strong><strong>App.js </strong></strong>before <code class=\"language-text\">&#x3C;Form /></code> :</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"jsx\"><pre class=\"language-jsx\"><code class=\"language-jsx\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;</span>div</span> <span class=\"token attr-name\">id</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>result<span class=\"token punctuation\">\"</span></span> <span class=\"token attr-name\">style</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token punctuation\">{</span><span class=\"token literal-property property\">marginBottom</span><span class=\"token operator\">:</span> <span class=\"token string\">'15px'</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;/</span>div</span><span class=\"token punctuation\">></span></span></code></pre></div><p>Alright, now go to your website and discover all new trivia about numbers!</p><hr><h2 id=\"conclusion\">Conclusion</h2><p>You just created a React app and used some React Hooks! Of course, there’s still more to explore and learn, so be sure to head to the <a href=\"https://reactjs.org/docs/hooks-intro.html\" rel=\"noopener nofollow\">docs</a> to learn more about React Hooks.</p>","htmlAst":{"type":"root","children":[{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Hooks have been officially added to React as of React 16.8. One of the main benefits of Hooks in React is that you can use state and effect (which is generally a combination of different life cycles into one) in a component without creating a class."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that gives the user some options to pick from in order to generate some random number trivia."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"You can check out the demo for the website "},{"type":"element","tagName":"a","properties":{"href":"http://numbers-trivia.surge.sh/","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"here"}]},{"type":"text","value":", and the source code on the "},{"type":"element","tagName":"a","properties":{"href":"https://github.com/shahednasser/numbers-trivia","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"GitHub repository"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s first start by creating a react app. Since our website will be very simple, we will use the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"create-react-app"}]},{"type":"text","value":" command. If you don’t have it installed, you can install it using "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"npm"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"."}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Run the following in your terminal or CMD:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"shell"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"npm"}]},{"type":"text","value":" i -g create-react-app"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This will install "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"create-react-app"}]},{"type":"text","value":" globally."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now we can create our React app:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"shell"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-shell"]},"children":[{"type":"text","value":"create-react-app numbers-trivia"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Running this command will create a directory in the working directory with the name you supply for the React app. I named it "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"numbers-trivia"}]}]},{"type":"text","value":" but you can call it whatever you want."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Inside that directory, it will also install all the packages and files needed to run the website. It will install packages like "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"react"}]}]},{"type":"text","value":", "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"react-dom"}]}]},{"type":"text","value":", "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"react-scripts"}]}]},{"type":"text","value":" and more."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Once it’s done, change into the newly created directory and start the server:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"shell"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","builtin","class-name"]},"children":[{"type":"text","value":"cd"}]},{"type":"text","value":" numbers-trivia\n"},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"npm"}]},{"type":"text","value":" start"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Once you start the server, a web page of your website in your favorite browser will open. You will see a page with just the logo and a link to learn React."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Before we start changing the page, if you are not familiar with React, let’s take a look at the structure of our React app. It should look something like this:"}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-image-card"]},"children":[{"type":"element","tagName":"img","properties":{"src":"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_R1irPlPj9UsboCM_KI5CgA.png","className":["kg-image"],"alt":"","loading":"lazy"},"children":[]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In our root directory, we will find a bunch of directories. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"node_modules "}]}]},{"type":"text","value":"holds all the packages React needs to run and any package you might add. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"public "}]}]},{"type":"text","value":"holds the files our server serves."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The directory that we will spend most of our time in is the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"src"}]}]},{"type":"text","value":" directory. This directory will hold all of our React components."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"As you can see there are a bunch of files in that directory. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index.js"}]}]},{"type":"text","value":" is basically the file that renders our highest React component."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We only have one React component right now which is in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js. "}]}]},{"type":"text","value":"If you open it, you will find the code that renders the logo with the link to learn React that you currently see on the website."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"So, in order to see how changing our App component will change the content of the website, let’s modify the code by removing the current content and replacing it with our favorite phrase: “Hello, World!”"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":" Component "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" logo "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./logo.svg'"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./App.css'"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"class"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","class-name"]},"children":[{"type":"text","value":"App"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"extends"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","class-name"]},"children":[{"type":"text","value":"Component"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"render"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"header className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App-header\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n           "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"h1"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Hello"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" World"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"h1"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"header"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" App"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We just replaced the content of the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"header"}]}]},{"type":"text","value":" element. Now, if your server is still running you will see that your page updated without you refreshing it, and you will see that the previous content is replaced with "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Hello, World!"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"So now we know how and where we should edit our React components in order to get the result we want. We can go ahead and start with our objective."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What we’ll do for this website is the following:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Show a welcome message the first time the user opens the website, then replace it with a message prompting the user to try the generator."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Render a form with "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"text "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"select"}]}]},{"type":"text","value":" inputs. The "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"text "}]}]},{"type":"text","value":"input is where the user can enter the number they want to see trivia about, and the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"select "}]}]},{"type":"text","value":"input will provide the user with options related to the trivia."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"On submitting the form, send a request to "},{"type":"element","tagName":"a","properties":{"href":"http://numbersapi.com/","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"this API"}]},{"type":"text","value":" to fetch the trivia we need."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Render the trivia for the user to see it."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s start by organizing our directory structure first. In React it’s good practice to create a directory inside "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"src"}]}]},{"type":"text","value":" holding all the components. We’ll create a directory called "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"components"}]}]},{"type":"text","value":". Once you create the directory, move "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js"}]}]},{"type":"text","value":" into there. We will also create a directory called "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"styles"}]}]},{"type":"text","value":" and move "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.css "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index.css "}]}]},{"type":"text","value":"into it."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"When you do that, you will need to change the imports in your files as following:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index.js:"}]}]}]}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" ReactDOM "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react-dom'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'../styles/index.css'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" App "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./components/App'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":"  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"as"}]},{"type":"text","value":" serviceWorker "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./serviceWorker'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"2. in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js:"}]}]}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":" Component "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" logo "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./logo.svg'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'../styles/App.css'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Our directory structure should look like this now:"}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-image-card"]},"children":[{"type":"element","tagName":"img","properties":{"src":"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_Aqgelb3qbhJiESUbGGNUoQ.png","className":["kg-image"],"alt":"","loading":"lazy"},"children":[]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We will go ahead now and start building our webpage."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The first thing in our objectives list is showing a welcome message when the user first opens the webpage. It will show up for 3 seconds, and then changes to another message that will prompt the user to try out the trivia generator."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Without hooks, this could be done by using React’s lifecycle method "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"componentDidMount"}]},{"type":"element","tagName":"em","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"which runs right after the component first renders."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we can use the "},{"type":"element","tagName":"a","properties":{"href":"https://reactjs.org/docs/hooks-effect.html","rel":["noopener","nofollow"]},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"text","value":"effect hook"}]}]}]},{"type":"element","tagName":"em","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"instead. It will look something like this:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","comment"]},"children":[{"type":"text","value":"//perform something post render"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The function you pass to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"text","value":" will be executed after every render. This combines the lifecycles methods "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"componentDidMount"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"componentDidUpdate"}]},{"type":"text","value":" into one."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What if you want to do something just after the first time the component renders, like in "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"componentDidMount"}]},{"type":"text","value":"? You can do this by passing a second parameter to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"accepts an array as a second parameter. This parameter is used as a condition on when to perform the passed function. So, let’s say you want to change a counter only after the variable "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"counter "}]}]},{"type":"text","value":"changes, you can do it like so:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" document"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"title "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","template-string"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","template-punctuation","string"]},"children":[{"type":"text","value":"`"}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"You have clicked "}]},{"type":"element","tagName":"span","properties":{"className":["token","interpolation"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","interpolation-punctuation","punctuation"]},"children":[{"type":"text","value":"${"}]},{"type":"text","value":"counter"},{"type":"element","tagName":"span","properties":{"className":["token","interpolation-punctuation","punctuation"]},"children":[{"type":"text","value":"}"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":" times"}]},{"type":"element","tagName":"span","properties":{"className":["token","template-punctuation","string"]},"children":[{"type":"text","value":"`"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"text","value":"counter"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This way, the function passed to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"text","value":" will run after render only if the value for "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"counter"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"changes."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"If we want the function to run only after the first render, we can do that by passing an "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"empty"}]}]},{"type":"text","value":" array as the second parameter."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s come back now to what we want to do. We want to show a welcome message when the user first opens the page, then change that message after 3 seconds. We can do that by adding the following inside "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js"}]}]},{"type":"text","value":":"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"useEffect"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" Form "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./Form'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'../styles/App.css'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"App"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setTimeout"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" welcomeMessage "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" document"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"getElementById"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"welcomeMessage\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n       welcomeMessage"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"innerHTML "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"Try Out Our Trivia Generator!\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","number"]},"children":[{"type":"text","value":"3000"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"header className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App-header\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"h1 id"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"welcomeMessage\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Welcome to Numbers Trivia"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"h1"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"Form "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"header"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" App"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here’s what we’re doing:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 1:"}]}]},{"type":"text","value":" We added an import for "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 4: "}]}]},{"type":"text","value":"We changed our class component into a function component"}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 5–10: "}]}]},{"type":"text","value":"we added an effect to our function component. This effect sets a timer after 3 seconds that will change the text in the element with the id "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"welcomeMessage"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":". "}]}]},{"type":"text","value":"Because we passed an "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"empty"}]}]},{"type":"text","value":" array to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"text","value":", this effect will only run once."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 11–17: "}]}]},{"type":"text","value":"We replaced the previous code in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js "}]}]},{"type":"text","value":"to render an "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"h1 "}]}]},{"type":"text","value":"element having the id "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"welcomeMessage"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":", "}]}]},{"type":"text","value":"which is our target element."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Okay, now go to our web page and see the changes. At first, the welcome message “"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Welcome to Numbers Trivia!"}]}]},{"type":"text","value":"” will show up, then 3 seconds later it will change into “"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Try Out Our Trivia Generator!"}]}]},{"type":"text","value":"” We just used a React Hook!"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Next, let’s create our form input elements. To do that, we will create a new React component called "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":". "}]}]},{"type":"text","value":"Create in the directory "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"components"}]}]},{"type":"text","value":" the file "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form.js. "}]}]},{"type":"text","value":"For now, it will just include the following:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"props"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" Form"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This will create the new React component. We’re just importing React, then we’re creating a function called Form. As we said earlier in the tutorial, with the use of hooks we can now create components as stateful functions rather than classes. And in the last line, we’re exporting "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form"}]}]},{"type":"text","value":" in order to import it in other files."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In the form, we will have a "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"text "}]}]},{"type":"text","value":"input and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"select "}]}]},{"type":"text","value":"elements. This is based on the API we’re using. In the API, two parameters can be sent:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"number: "}]}]},{"type":"text","value":"the number you want to get the trivia for. It can be an "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"integer"}]}]},{"type":"text","value":", a date of the form "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"month/day, "}]}]},{"type":"text","value":"or the keyword "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"random "}]}]},{"type":"text","value":"which will retrieve facts about a random number."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"type: "}]}]},{"type":"text","value":"the type of information you want to get. There are a few types: "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"math, date, year, "}]}]},{"type":"text","value":"or, the default, "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"trivia."}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We will consider the text input element as optional. If the user does not enter a number or a date, we will send the keyword "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"random"}]}]},{"type":"text","value":" for the number element."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s add the following code inside the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form"}]}]},{"type":"text","value":" function in order to render our form:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"props"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"form"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"input type"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"text\""}]},{"type":"text","value":" name"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"number\""}]},{"type":"text","value":" placeholder"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"Enter a number (Optional)\""}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"select name"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"type\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n               "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"trivia\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Trivia"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n               "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"math\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Math"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n               "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"date\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Date"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n               "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"year\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Year"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"select"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"button type"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"submit\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Generate"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"button"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"form"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This will create the form with the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"text "}]}]},{"type":"text","value":"input and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"select "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"button "}]}]},{"type":"text","value":"elements."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"After that, we need to import and render the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form"}]}]},{"type":"text","value":" component in our "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App "}]}]},{"type":"text","value":"component:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"useEffect"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" Form "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./Form'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'../styles/App.css'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"App"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setTimeout"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" welcomeMessage "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" document"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"getElementById"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"welcomeMessage\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n       welcomeMessage"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"innerHTML "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"Try Out Our Trivia Generator!\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","number"]},"children":[{"type":"text","value":"3000"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"header className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App-header\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"h1 id"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"welcomeMessage\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Welcome to Numbers Trivia"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"h1"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"Form "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"header"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" App"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We have changed the imports to import our "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"component, and we added "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"<Form />"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"to render the form."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s also add more styles just to make our form look a little better. Add the following at the end of "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.css"}]}]},{"type":"text","value":":"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"form"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"font-size"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 15px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"form input, form select"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"padding"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 5px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"form select"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"width"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 100%"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"form div"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"margin-bottom"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 8px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"If you refresh the page now, you will find it has changed and now it’s showing our form."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we need to add some logic to our form. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"On Submit"}]}]},{"type":"text","value":", we need to get the values of our input elements, then call the API to retrieve the results."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"To handle form elements and their values, you need to use the state of the component. You make the value of the element equal to a property in the state of the component."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Before hooks, in order to get the value in the state you would have to use "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"this.state.value"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":", "}]}]},{"type":"text","value":"and then to set the state, you will need to call "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"this.setState"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, you can use the state hook. The state hook is the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"function. It accepts one argument, which is the initial value, and it returns a pair of values: the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"current state"}]}]},{"type":"text","value":" and a "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"function"}]}]},{"type":"text","value":" that updates it. Then, you will be able to access the current state using the first returned value, and update it using the second returned value which is the function."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here’s an example:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"const"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"text","value":"count"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" setCount"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","number"]},"children":[{"type":"text","value":"0"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"in this example, we call the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"hook and pass it 0, and we set the returned value equal to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"count"}]},{"type":"text","value":" and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"setCount"}]},{"type":"text","value":". This means that we have created state variable called "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"count"}]},{"type":"text","value":". Its initial value is 0, and to change its value we can use "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"setCount"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"For our "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"component, we need two state variables, one for the text"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"input which we will call "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"number"}]},{"type":"text","value":", and one for the select"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"input which we will call "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"type"}]},{"type":"text","value":". Then, on change event for these two input elements, we will change the values for "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"number"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"type"}]},{"type":"text","value":" using the function returned by "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"setState"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"."}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Open our "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"component and change it to the following:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":" useState "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"props"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"text","value":"number"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" setNumber"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"random\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"text","value":"type"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" setType"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"trivia\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"onNumberChanged"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"e"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" value "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" e"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"target"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"trim"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"if"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"length"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n      "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setNumber"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"random\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","comment"]},"children":[{"type":"text","value":"//default value"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"else"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n      "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setNumber"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"onTypeChanged"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"e"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" value "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" e"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"target"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"trim"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"if"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"length"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n      "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setType"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"trivia\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","comment"]},"children":[{"type":"text","value":"//default value"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"else"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n      "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setType"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"form"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"input type"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"text\""}]},{"type":"text","value":" name"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"number\""}]},{"type":"text","value":" placeholder"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"Enter a number (Optional)\""}]},{"type":"text","value":" value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"number"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" onChange"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"onNumberChanged"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"select name"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"type\""}]},{"type":"text","value":" value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"type"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" onChange"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"onTypeChanged"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n                "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"trivia\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Trivia"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n                "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"math\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Math"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n                "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"date\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Date"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n                "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"year\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Year"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"select"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"button type"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"submit\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Generate"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"button"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"form"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" Form"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 1: "}]}]},{"type":"text","value":"add an import for "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"text","value":" hook."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 3–4: "}]}]},{"type":"text","value":"create two state variables "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"number"}]},{"type":"text","value":" and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"type"}]},{"type":"text","value":" using "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"text","value":" . Here we pass "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"random "}]}]},{"type":"text","value":"as the initial value for number, and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"trivia "}]}]},{"type":"text","value":"as initial value for type because they are the default values for the parameters in the API."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 5–10: "}]}]},{"type":"text","value":"implement input change handler functions for both text and select inputs, where we change the value of the state variables using the functions returned by "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"text","value":" . If the value is unset, we automatically change the values to the default value."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 13: "}]}]},{"type":"text","value":"pass the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onNumberChanged"}]},{"type":"text","value":" function to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onChange"}]},{"type":"text","value":" event for text input."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 16: "}]}]},{"type":"text","value":"pass the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onTypeChanged"}]},{"type":"text","value":" function to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onChange"}]},{"type":"text","value":" event for select input."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In addition, let’s go back to our "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"App"}]},{"type":"text","value":" component to modify it and use states. Instead of modifying our welcome message by changing the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"innerHTML"}]},{"type":"text","value":" of the element, we will use a state. Our App component should now be like this:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"text"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-text"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"import React, {useEffect, useState} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n  const [ welcomeMessage, setWelcomeMessage ] = useState(\n    \"Welcome to Numbers Trivia!\",\n  );\nuseEffect(() => {\n    setTimeout(() => {\n      setWelcomeMessage(\"Try Out Our Trivia Generator!\");\n    }, 3000);\n  }, []);\nreturn (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <h1>{welcomeMessage}</h1>\n      </header>\n      <Form/>\n    </div>\n  );\n}\nexport default App;"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we are using "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"text","value":" to declare and initialize our welcome message. It will return "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"welcomeMessage"}]},{"type":"text","value":" , our state variable, and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"setWelcomeMessage"}]},{"type":"text","value":" , which we will use to change the value of "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"welcomeMessage"}]},{"type":"text","value":" after 3 seconds from “"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Welcome to Numbers Trivia!"}]}]},{"type":"text","value":"” to “"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Try Out Our Trivia Generator!"}]}]},{"type":"text","value":"”"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What’s left now is to add a function to handle the form’s "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onSubmit"}]},{"type":"text","value":" event. On submit, we will send a request to the API with our parameters, then display the result."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In order to perform the request, we need to install "},{"type":"element","tagName":"a","properties":{"href":"https://github.com/axios/axios","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"axios"}]},{"type":"text","value":":"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"shell"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"npm"}]},{"type":"text","value":" i axios"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Then, require axios at the beginning of "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form.js:"}]}]}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"const"}]},{"type":"text","value":" axios "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"require"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'axios'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, add the following function below "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onTypeChanged"}]},{"type":"text","value":" in our "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form"}]}]},{"type":"text","value":" component:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"onSubmit"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"e"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n  e"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"preventDefault"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n  axios"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"get"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'http://numbersapi.com/'"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"+"}]},{"type":"text","value":" number "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"+"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'/'"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"+"}]},{"type":"text","value":" type"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"then"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"response"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" elm "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" document"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"getElementById"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'result'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n         elm"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"innerHTML "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" response"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"data"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"catch"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"e"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n         console"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"log"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"error\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" e"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","comment"]},"children":[{"type":"text","value":"//simple error handling"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We’re just performing a request to the API, passing the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"number"}]},{"type":"text","value":" and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"type"}]},{"type":"text","value":" then displaying the result in an element of id "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"result"}]},{"type":"text","value":" (which we will add in a minute). In case of an error, we’re just displaying it in the console just as a simple error handling."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, let’s add this function as the handler for the form "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onSubmit"}]},{"type":"text","value":" event in the return statement in Form.js:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"jsx"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-jsx"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-jsx"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"form"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"onSubmit"}]},{"type":"element","tagName":"span","properties":{"className":["token","script","language-javascript"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","script-punctuation","punctuation"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"onSubmit"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The only thing left is to add the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"#result"}]},{"type":"text","value":" element. We can add it in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js "}]}]},{"type":"text","value":"before "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"<Form />"}]},{"type":"text","value":" :"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"jsx"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-jsx"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-jsx"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"id"}]},{"type":"element","tagName":"span","properties":{"className":["token","attr-value"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation","attr-equals"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]},{"type":"text","value":"result"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"style"}]},{"type":"element","tagName":"span","properties":{"className":["token","script","language-javascript"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","script-punctuation","punctuation"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"element","tagName":"span","properties":{"className":["token","literal-property","property"]},"children":[{"type":"text","value":"marginBottom"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'15px'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"</"}]},{"type":"text","value":"div"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Alright, now go to your website and discover all new trivia about numbers!"}]},{"type":"element","tagName":"hr","properties":{},"children":[]},{"type":"element","tagName":"h2","properties":{"id":"conclusion"},"children":[{"type":"text","value":"Conclusion"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"You just created a React app and used some React Hooks! Of course, there’s still more to explore and learn, so be sure to head to the "},{"type":"element","tagName":"a","properties":{"href":"https://reactjs.org/docs/hooks-intro.html","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"docs"}]},{"type":"text","value":" to learn more about React Hooks."}]}],"data":{"quirksMode":false}},"tableOfContents":[{"id":"conclusion","heading":"Conclusion"}]},"featureImageSharp":{"base":"1_-Ijet6kVJqGgul6adezDLQ.png","publicURL":"/static/811e7e5724a90f775f8832f17c9353ff/1_-Ijet6kVJqGgul6adezDLQ.png","imageMeta":{"width":700,"height":350},"childImageSharp":{"fluid":{"base64":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAKCAIAAAA7N+mxAAAACXBIWXMAAAsTAAALEwEAmpwYAAABLElEQVQoz5WS3UrDQBCF8yDd7M5MdwesMf2NpSaUPkAvJCUNUqxKoNKgEStUsMU7vRJ8ZKFp2kYv1MMy7M03ezhnLTwU0fb8Tdb+CgBSbue3jb/DWpuTetWwcVwA2FCU7yyWEGxUhonAFlxvdW/uzubL5vkFgEIAIQQiMjMiGmOEEMystcaCt3LDpE07mvaXb4PVR/CwNt3A67Rns9nldBqORkmSxHGcZdlkMvF937bt3FQBG26Pr/vP74PXzyBbm17/1PPSNE2SJAzDeZrGcfy4WERRNBwOK5XKAUykbMEtr3f75N+/dMZXoBQiSimZ2XEcw1yr1aSUjUaDmaFke/M6ac1uUx8dG8fFIjAAUErlk4iklD8C21dlg1K7qqjQLnkq12aVK63+65N8AWEWZr2hm3MKAAAAAElFTkSuQmCC","aspectRatio":2,"src":"/static/811e7e5724a90f775f8832f17c9353ff/60290/1_-Ijet6kVJqGgul6adezDLQ.png","srcSet":"/static/811e7e5724a90f775f8832f17c9353ff/bcfcb/1_-Ijet6kVJqGgul6adezDLQ.png 260w,\n/static/811e7e5724a90f775f8832f17c9353ff/19d75/1_-Ijet6kVJqGgul6adezDLQ.png 520w,\n/static/811e7e5724a90f775f8832f17c9353ff/60290/1_-Ijet6kVJqGgul6adezDLQ.png 700w","srcWebp":"/static/811e7e5724a90f775f8832f17c9353ff/89afa/1_-Ijet6kVJqGgul6adezDLQ.webp","srcSetWebp":"/static/811e7e5724a90f775f8832f17c9353ff/dc8f3/1_-Ijet6kVJqGgul6adezDLQ.webp 260w,\n/static/811e7e5724a90f775f8832f17c9353ff/2db4b/1_-Ijet6kVJqGgul6adezDLQ.webp 520w,\n/static/811e7e5724a90f775f8832f17c9353ff/89afa/1_-Ijet6kVJqGgul6adezDLQ.webp 700w","sizes":"(max-width: 700px) 100vw, 700px"}}}},"ghostPost":{"id":"Ghost__Post__6127ba1b3ed159214d382e72","title":"React Hooks Tutorial — Create a Number Trivia Generator Website","slug":"react-hooks-tutorial-create-a-number-trivia-generator-website","featured":false,"feature_image":"https://res-1.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_-Ijet6kVJqGgul6adezDLQ.png","excerpt":"In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that generates number trivia.","custom_excerpt":"In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that generates number trivia.","visibility":"public","created_at_pretty":"10 Nov 2020","published_at_pretty":"16 Apr 2019","updated_at_pretty":"10 Nov 2020","created_at":"2020-11-10T07:34:40.000+00:00","published_at":"2019-04-16T07:34:00.000+00:00","updated_at":"2020-11-10T08:20:26.000+00:00","meta_title":null,"meta_description":null,"og_description":null,"og_image":null,"og_title":null,"twitter_description":null,"twitter_image":null,"twitter_title":null,"authors":[{"slug":"shahed","url":"https://backend.shahednasser.com/author/shahed/","name":"Shahed Nasser","bio":null,"cover_image":null,"profile_image":"https://backend.shahednasser.com/content/images/2022/03/IMG_0591.jpg","location":null,"website":null,"twitter":null,"facebook":null,"meta_title":null,"meta_description":null,"coverImageSharp":null,"profileImageSharp":null}],"primary_author":{"slug":"shahed","url":"https://backend.shahednasser.com/author/shahed/","name":"Shahed Nasser","bio":null,"cover_image":null,"profile_image":"https://backend.shahednasser.com/content/images/2022/03/IMG_0591.jpg","location":null,"website":null,"twitter":null,"facebook":null,"meta_title":null,"meta_description":null,"coverImageSharp":null,"profileImageSharp":{"base":"IMG_0591.jpg","publicURL":"/static/ceb49c3c631485453e71e00d7f84b069/IMG_0591.jpg","imageMeta":{"width":1182,"height":1179},"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAMEAQL/xAAWAQEBAQAAAAAAAAAAAAAAAAADBAL/2gAMAwEAAhADEAAAAdXiFM6i0CohUWXoKn//xAAcEAACAgIDAAAAAAAAAAAAAAACAwESBBEhM0H/2gAIAQEAAQUCWySE3WEr7SzbXjAj4iKty+sOQ//EABYRAQEBAAAAAAAAAAAAAAAAAAERIP/aAAgBAwEBPwEhj//EABQRAQAAAAAAAAAAAAAAAAAAACD/2gAIAQIBAT8BH//EAB4QAAIBBAMBAAAAAAAAAAAAAAABIRESMUECECJx/9oACAEBAAY/ApVGWvOjzgtUwLlTZA0sdL4f/8QAHBAAAwACAwEAAAAAAAAAAAAAAAERITFBkbHB/9oACAEBAAE/IahkCy+N2GwZpjQiJHJCspUFY0QrSi+HqiW2rgf/2gAMAwEAAgADAAAAEPw3/wD/xAAYEQEBAAMAAAAAAAAAAAAAAAAAARExQf/aAAgBAwEBPxCtjDqP/8QAFxEBAQEBAAAAAAAAAAAAAAAAAQAxEf/aAAgBAgEBPxBFus6Tt//EAB8QAQEAAgIBBQAAAAAAAAAAAAERACExQWFRcYGR0f/aAAgBAQABPxAuaBPPzkO1wyX7F4wkwXanfZrFQgeqE9JgS14vVOvrERIJomVBKwt2jebAeP0yVa8h1n//2Q==","aspectRatio":1,"src":"/static/ceb49c3c631485453e71e00d7f84b069/31709/IMG_0591.jpg","srcSet":"/static/ceb49c3c631485453e71e00d7f84b069/f340b/IMG_0591.jpg 28w,\n/static/ceb49c3c631485453e71e00d7f84b069/22d64/IMG_0591.jpg 55w,\n/static/ceb49c3c631485453e71e00d7f84b069/31709/IMG_0591.jpg 110w,\n/static/ceb49c3c631485453e71e00d7f84b069/aa249/IMG_0591.jpg 165w,\n/static/ceb49c3c631485453e71e00d7f84b069/0dc33/IMG_0591.jpg 220w,\n/static/ceb49c3c631485453e71e00d7f84b069/d8257/IMG_0591.jpg 1182w","srcWebp":"/static/ceb49c3c631485453e71e00d7f84b069/8678c/IMG_0591.webp","srcSetWebp":"/static/ceb49c3c631485453e71e00d7f84b069/59cda/IMG_0591.webp 28w,\n/static/ceb49c3c631485453e71e00d7f84b069/7da75/IMG_0591.webp 55w,\n/static/ceb49c3c631485453e71e00d7f84b069/8678c/IMG_0591.webp 110w,\n/static/ceb49c3c631485453e71e00d7f84b069/f282e/IMG_0591.webp 165w,\n/static/ceb49c3c631485453e71e00d7f84b069/a7b21/IMG_0591.webp 220w,\n/static/ceb49c3c631485453e71e00d7f84b069/63099/IMG_0591.webp 1182w","sizes":"(max-width: 110px) 100vw, 110px"}}}},"primary_tag":null,"tags":[],"plaintext":"Hooks have been officially added to React as of React 16.8. One of the main\nbenefits of Hooks in React is that you can use state and effect (which is\ngenerally a combination of different life cycles into one) in a component\nwithout creating a class.\n\nIn this tutorial, you’ll learn how to exactly use hooks in React. We will build\na simple website that gives the user some options to pick from in order to\ngenerate some random number trivia.\n\nYou can check out the demo for the website here\n[http://numbers-trivia.surge.sh/], and the source code on the GitHub repository\n[https://github.com/shahednasser/numbers-trivia].\n\nLet’s first start by creating a react app. Since our website will be very\nsimple, we will use the create-react-app command. If you don’t have it\ninstalled, you can install it using npm.\n\nRun the following in your terminal or CMD:\n\nnpm i -g create-react-app\n\nThis will install create-react-app globally.\n\nNow we can create our React app:\n\ncreate-react-app numbers-trivia\n\nRunning this command will create a directory in the working directory with the\nname you supply for the React app. I named it numbers-trivia but you can call it\nwhatever you want.\n\nInside that directory, it will also install all the packages and files needed to\nrun the website. It will install packages like react, react-dom, react-scripts \nand more.\n\nOnce it’s done, change into the newly created directory and start the server:\n\ncd numbers-trivia\nnpm start\n\nOnce you start the server, a web page of your website in your favorite browser\nwill open. You will see a page with just the logo and a link to learn React.\n\nBefore we start changing the page, if you are not familiar with React, let’s\ntake a look at the structure of our React app. It should look something like\nthis:\n\nIn our root directory, we will find a bunch of directories. node_modules holds\nall the packages React needs to run and any package you might add. public holds\nthe files our server serves.\n\nThe directory that we will spend most of our time in is the src directory. This\ndirectory will hold all of our React components.\n\nAs you can see there are a bunch of files in that directory. index.js is\nbasically the file that renders our highest React component.\n\nWe only have one React component right now which is in App.js. If you open it,\nyou will find the code that renders the logo with the link to learn React that\nyou currently see on the website.\n\nSo, in order to see how changing our App component will change the content of\nthe website, let’s modify the code by removing the current content and replacing\nit with our favorite phrase: “Hello, World!”\n\nimport React, { Component } from 'react' \nimport logo from './logo.svg' \nimport './App.css'  \nclass App extends Component {\n   render() {\n     return (\n       <div className=\"App\">\n         <header className=\"App-header\">\n           <h1>Hello, World!</h1>\n         </header>\n       </div>\n     )\n   }\n }\nexport default App\n\nWe just replaced the content of the header element. Now, if your server is still\nrunning you will see that your page updated without you refreshing it, and you\nwill see that the previous content is replaced with Hello, World!\n\nSo now we know how and where we should edit our React components in order to get\nthe result we want. We can go ahead and start with our objective.\n\nWhat we’ll do for this website is the following:\n\n 1. Show a welcome message the first time the user opens the website, then\n    replace it with a message prompting the user to try the generator.\n 2. Render a form with text and select inputs. The text input is where the user\n    can enter the number they want to see trivia about, and the select input\n    will provide the user with options related to the trivia.\n 3. On submitting the form, send a request to this API [http://numbersapi.com/] \n    to fetch the trivia we need.\n 4. Render the trivia for the user to see it.\n\nLet’s start by organizing our directory structure first. In React it’s good\npractice to create a directory inside src holding all the components. We’ll\ncreate a directory called components. Once you create the directory, move App.js \ninto there. We will also create a directory called styles and move App.css and \nindex.css into it.\n\nWhen you do that, you will need to change the imports in your files as\nfollowing:\n\n 1. in index.js:\n\nimport React from 'react'; \nimport ReactDOM from 'react-dom'; \nimport '../styles/index.css'; \nimport App from './components/App'; \nimport  as serviceWorker from './serviceWorker';\n\n2. in App.js:\n\nimport React, { Component } from 'react'; \nimport logo from './logo.svg'; \nimport '../styles/App.css';\n\nOur directory structure should look like this now:\n\nWe will go ahead now and start building our webpage.\n\nThe first thing in our objectives list is showing a welcome message when the\nuser first opens the webpage. It will show up for 3 seconds, and then changes to\nanother message that will prompt the user to try out the trivia generator.\n\nWithout hooks, this could be done by using React’s lifecycle method \ncomponentDidMount which runs right after the component first renders.\n\nNow, we can use the effect hook [https://reactjs.org/docs/hooks-effect.html] \ninstead. It will look something like this:\n\nuseEffect(() => {\n  //perform something post render\n});\n\nThe function you pass to useEffect will be executed after every render. This\ncombines the lifecycles methods componentDidMount and componentDidUpdate into\none.\n\nWhat if you want to do something just after the first time the component\nrenders, like in componentDidMount? You can do this by passing a second\nparameter to useEffect.\n\nuseEffect accepts an array as a second parameter. This parameter is used as a\ncondition on when to perform the passed function. So, let’s say you want to\nchange a counter only after the variable counter changes, you can do it like so:\n\nuseEffect(() => document.title = `You have clicked ${counter} times`, [counter]);\n\nThis way, the function passed to useEffect will run after render only if the\nvalue for counter changes.\n\nIf we want the function to run only after the first render, we can do that by\npassing an empty array as the second parameter.\n\nLet’s come back now to what we want to do. We want to show a welcome message\nwhen the user first opens the page, then change that message after 3 seconds. We\ncan do that by adding the following inside App.js:\n\nimport React, {useEffect} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n   useEffect(() => {\n     setTimeout(() => {\n       let welcomeMessage = document.getElementById(\"welcomeMessage\");\n       welcomeMessage.innerHTML = \"Try Out Our Trivia Generator!\";\n     }, 3000);\n   }, []);\n   return (\n     <div className=\"App\">\n       <header className=\"App-header\">\n         <h1 id=\"welcomeMessage\">Welcome to Numbers Trivia!</h1>\n         <Form />\n       </header>\n     </div>\n   ); }  \nexport default App;\n\nHere’s what we’re doing:\n\n 1. Line 1: We added an import for useEffect\n 2. Line 4: We changed our class component into a function component\n 3. Line 5–10: we added an effect to our function component. This effect sets a\n    timer after 3 seconds that will change the text in the element with the id \n    welcomeMessage. Because we passed an empty array to useEffect, this effect\n    will only run once.\n 4. Line 11–17: We replaced the previous code in App.js to render an h1 element\n    having the id welcomeMessage, which is our target element.\n\nOkay, now go to our web page and see the changes. At first, the welcome message\n“Welcome to Numbers Trivia!” will show up, then 3 seconds later it will change\ninto “Try Out Our Trivia Generator!” We just used a React Hook!\n\nNext, let’s create our form input elements. To do that, we will create a new\nReact component called Form. Create in the directory components the file \nForm.js. For now, it will just include the following:\n\nimport React from 'react';  \nfunction Form(props){\n}\nexport default Form;\n\nThis will create the new React component. We’re just importing React, then we’re\ncreating a function called Form. As we said earlier in the tutorial, with the\nuse of hooks we can now create components as stateful functions rather than\nclasses. And in the last line, we’re exporting Form in order to import it in\nother files.\n\nIn the form, we will have a text input and select elements. This is based on the\nAPI we’re using. In the API, two parameters can be sent:\n\n 1. number: the number you want to get the trivia for. It can be an integer, a\n    date of the form month/day, or the keyword random which will retrieve facts\n    about a random number.\n 2. type: the type of information you want to get. There are a few types: math,\n    date, year, or, the default, trivia.\n\nWe will consider the text input element as optional. If the user does not enter\na number or a date, we will send the keyword random for the number element.\n\nLet’s add the following code inside the Form function in order to render our\nform:\n\nfunction Form(props){\n  return (<form>\n             <div>\n              <input type=\"text\" name=\"number\" placeholder=\"Enter a number (Optional)\" />\n             </div>\n             <div>\n              <select name=\"type\">\n               <option value=\"trivia\">Trivia</option>\n               <option value=\"math\">Math</option>\n               <option value=\"date\">Date</option>\n               <option value=\"year\">Year</option>\n              </select>\n             </div>\n             <button type=\"submit\">Generate</button>\n            </form>); \n}\n\nThis will create the form with the text input and select and button elements.\n\nAfter that, we need to import and render the Form component in our App \ncomponent:\n\nimport React, {useEffect} from 'react';\nimport Form from './Form';\nimport '../styles/App.css';  \nfunction App() {\n   useEffect(() => {\n     setTimeout(() => {\n       let welcomeMessage = document.getElementById(\"welcomeMessage\");\n       welcomeMessage.innerHTML = \"Try Out Our Trivia Generator!\";\n     }, 3000);\n   }, []);\n   return (\n     <div className=\"App\">\n       <header className=\"App-header\">\n         <h1 id=\"welcomeMessage\">Welcome to Numbers Trivia!</h1>\n         <Form />\n       </header>\n     </div>\n   );\n }\nexport default App;\n\nWe have changed the imports to import our Form component, and we added <Form /> \nto render the form.\n\nLet’s also add more styles just to make our form look a little better. Add the\nfollowing at the end of App.css:\n\nform {\n   font-size: 15px;\n}  \nform input, form select {\n   padding: 5px;\n}  \nform select {\n   width: 100%; \n}  \nform div {\n   margin-bottom: 8px;\n}\n\nIf you refresh the page now, you will find it has changed and now it’s showing\nour form.\n\nNow, we need to add some logic to our form. On Submit, we need to get the values\nof our input elements, then call the API to retrieve the results.\n\nTo handle form elements and their values, you need to use the state of the\ncomponent. You make the value of the element equal to a property in the state of\nthe component.\n\nBefore hooks, in order to get the value in the state you would have to use \nthis.state.value, and then to set the state, you will need to call this.setState\n.\n\nNow, you can use the state hook. The state hook is the useState function. It\naccepts one argument, which is the initial value, and it returns a pair of\nvalues: the current state and a function that updates it. Then, you will be able\nto access the current state using the first returned value, and update it using\nthe second returned value which is the function.\n\nHere’s an example:\n\nconst [count, setCount] = useState(0);\n\nin this example, we call the useState hook and pass it 0, and we set the\nreturned value equal to count and setCount. This means that we have created\nstate variable called count. Its initial value is 0, and to change its value we\ncan use setCount.\n\nFor our Form component, we need two state variables, one for the text input\nwhich we will call number, and one for the select input which we will call type.\nThen, on change event for these two input elements, we will change the values\nfor number and type using the function returned by setState.\n\nOpen our Form component and change it to the following:\n\nimport React, { useState } from 'react';\nfunction Form(props){\n  let [number, setNumber] = useState(\"random\");\n  let [type, setType] = useState(\"trivia\");\n  function onNumberChanged(e){\n    let value = e.target.value.trim();\n    if(!value.length){\n      setNumber(\"random\"); //default value\n    } else {\n      setNumber(value);\n    }\n  }\n  function onTypeChanged(e){\n    let value = e.target.value.trim();\n    if(!value.length){\n      setType(\"trivia\"); //default value\n    } else {\n      setType(value);\n    }\n  }\n  return (<form>\n            <div>\n              <input type=\"text\" name=\"number\" placeholder=\"Enter a number (Optional)\" value={number} onChange={onNumberChanged} />\n            </div>\n            <div>\n              <select name=\"type\" value={type} onChange={onTypeChanged}>\n                <option value=\"trivia\">Trivia</option>\n                <option value=\"math\">Math</option>\n                <option value=\"date\">Date</option>\n                <option value=\"year\">Year</option>\n              </select>\n            </div>\n            <button type=\"submit\">Generate</button>\n</form>);\n}\nexport default Form;\n\n 1. Line 1: add an import for useState hook.\n 2. Line 3–4: create two state variables number and type using useState . Here\n    we pass random as the initial value for number, and trivia as initial value\n    for type because they are the default values for the parameters in the API.\n 3. Line 5–10: implement input change handler functions for both text and select\n    inputs, where we change the value of the state variables using the functions\n    returned by useState . If the value is unset, we automatically change the\n    values to the default value.\n 4. Line 13: pass the onNumberChanged function to onChange event for text input.\n 5. Line 16: pass the onTypeChanged function to onChange event for select input.\n\nIn addition, let’s go back to our App component to modify it and use states.\nInstead of modifying our welcome message by changing the innerHTML of the\nelement, we will use a state. Our App component should now be like this:\n\nimport React, {useEffect, useState} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n  const [ welcomeMessage, setWelcomeMessage ] = useState(\n    \"Welcome to Numbers Trivia!\",\n  );\nuseEffect(() => {\n    setTimeout(() => {\n      setWelcomeMessage(\"Try Out Our Trivia Generator!\");\n    }, 3000);\n  }, []);\nreturn (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <h1>{welcomeMessage}</h1>\n      </header>\n      <Form/>\n    </div>\n  );\n}\nexport default App;\n\nNow, we are using useState to declare and initialize our welcome message. It\nwill return welcomeMessage , our state variable, and setWelcomeMessage , which\nwe will use to change the value of welcomeMessage after 3 seconds from “Welcome\nto Numbers Trivia!” to “Try Out Our Trivia Generator!”\n\nWhat’s left now is to add a function to handle the form’s onSubmit event. On\nsubmit, we will send a request to the API with our parameters, then display the\nresult.\n\nIn order to perform the request, we need to install axios\n[https://github.com/axios/axios]:\n\nnpm i axios\n\nThen, require axios at the beginning of Form.js:\n\nconst axios = require('axios');\n\nNow, add the following function below onTypeChanged in our Form component:\n\nfunction onSubmit(e){\n  e.preventDefault();\n  axios.get('http://numbersapi.com/' + number + '/' + type)\n       .then(function(response){\n         let elm = document.getElementById('result');\n         elm.innerHTML = response.data;\n       }).catch(function(e){\n         console.log(\"error\", e); //simple error handling\n       });\n}\n\nWe’re just performing a request to the API, passing the number and type then\ndisplaying the result in an element of id result (which we will add in a\nminute). In case of an error, we’re just displaying it in the console just as a\nsimple error handling.\n\nNow, let’s add this function as the handler for the form onSubmit event in the\nreturn statement in Form.js:\n\n<form onSubmit={onSubmit}>\n\nThe only thing left is to add the #result element. We can add it in App.js \nbefore <Form /> :\n\n<div id=\"result\" style={{marginBottom: '15px'}}></div>\n\nAlright, now go to your website and discover all new trivia about numbers!\n\n\n--------------------------------------------------------------------------------\n\nConclusion\nYou just created a React app and used some React Hooks! Of course, there’s still\nmore to explore and learn, so be sure to head to the docs\n[https://reactjs.org/docs/hooks-intro.html] to learn more about React Hooks.","html":"<p>Hooks have been officially added to React as of React 16.8. One of the main benefits of Hooks in React is that you can use state and effect (which is generally a combination of different life cycles into one) in a component without creating a class.</p><p>In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that gives the user some options to pick from in order to generate some random number trivia.</p><p>You can check out the demo for the website <a href=\"http://numbers-trivia.surge.sh/\" rel=\"noopener nofollow\">here</a>, and the source code on the <a href=\"https://github.com/shahednasser/numbers-trivia\" rel=\"noopener nofollow\">GitHub repository</a>.</p><p>Let’s first start by creating a react app. Since our website will be very simple, we will use the <code>create-react-app</code> command. If you don’t have it installed, you can install it using <code>npm</code><strong><strong>.</strong></strong></p><p>Run the following in your terminal or CMD:</p><pre><code class=\"language-Shell\">npm i -g create-react-app</code></pre><p>This will install <code>create-react-app</code> globally.</p><p>Now we can create our React app:</p><pre><code class=\"language-Shell\">create-react-app numbers-trivia</code></pre><p>Running this command will create a directory in the working directory with the name you supply for the React app. I named it <strong><strong>numbers-trivia</strong></strong> but you can call it whatever you want.</p><p>Inside that directory, it will also install all the packages and files needed to run the website. It will install packages like <strong><strong>react</strong></strong>, <strong><strong>react-dom</strong></strong>, <strong><strong>react-scripts</strong></strong> and more.</p><p>Once it’s done, change into the newly created directory and start the server:</p><pre><code class=\"language-Shell\">cd numbers-trivia\nnpm start</code></pre><p>Once you start the server, a web page of your website in your favorite browser will open. You will see a page with just the logo and a link to learn React.</p><p>Before we start changing the page, if you are not familiar with React, let’s take a look at the structure of our React app. It should look something like this:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_R1irPlPj9UsboCM_KI5CgA.png\" class=\"kg-image\" alt loading=\"lazy\"></figure><p>In our root directory, we will find a bunch of directories. <strong><strong>node_modules </strong></strong>holds all the packages React needs to run and any package you might add. <strong><strong>public </strong></strong>holds the files our server serves.</p><p>The directory that we will spend most of our time in is the <strong><strong>src</strong></strong> directory. This directory will hold all of our React components.</p><p>As you can see there are a bunch of files in that directory. <strong><strong>index.js</strong></strong> is basically the file that renders our highest React component.</p><p>We only have one React component right now which is in <strong><strong>App.js. </strong></strong>If you open it, you will find the code that renders the logo with the link to learn React that you currently see on the website.</p><p>So, in order to see how changing our App component will change the content of the website, let’s modify the code by removing the current content and replacing it with our favorite phrase: “Hello, World!”</p><pre><code class=\"language-JS\">import React, { Component } from 'react' \nimport logo from './logo.svg' \nimport './App.css'  \nclass App extends Component {\n   render() {\n     return (\n       &lt;div className=\"App\"&gt;\n         &lt;header className=\"App-header\"&gt;\n           &lt;h1&gt;Hello, World!&lt;/h1&gt;\n         &lt;/header&gt;\n       &lt;/div&gt;\n     )\n   }\n }\nexport default App</code></pre><p>We just replaced the content of the <strong><strong>header</strong></strong> element. Now, if your server is still running you will see that your page updated without you refreshing it, and you will see that the previous content is replaced with <strong><strong>Hello, World!</strong></strong></p><p>So now we know how and where we should edit our React components in order to get the result we want. We can go ahead and start with our objective.</p><p>What we’ll do for this website is the following:</p><ol><li>Show a welcome message the first time the user opens the website, then replace it with a message prompting the user to try the generator.</li><li>Render a form with <strong><strong>text </strong></strong>and <strong><strong>select</strong></strong> inputs. The <strong><strong>text </strong></strong>input is where the user can enter the number they want to see trivia about, and the <strong><strong>select </strong></strong>input will provide the user with options related to the trivia.</li><li>On submitting the form, send a request to <a href=\"http://numbersapi.com/\" rel=\"noopener nofollow\">this API</a> to fetch the trivia we need.</li><li>Render the trivia for the user to see it.</li></ol><p>Let’s start by organizing our directory structure first. In React it’s good practice to create a directory inside <strong><strong>src</strong></strong> holding all the components. We’ll create a directory called <strong><strong>components</strong></strong>. Once you create the directory, move <strong><strong>App.js</strong></strong> into there. We will also create a directory called <strong><strong>styles</strong></strong> and move <strong><strong>App.css </strong></strong>and <strong><strong>index.css </strong></strong>into it.</p><p>When you do that, you will need to change the imports in your files as following:</p><ol><li>in <strong><strong>index.js:</strong></strong></li></ol><pre><code class=\"language-JS\">import React from 'react'; \nimport ReactDOM from 'react-dom'; \nimport '../styles/index.css'; \nimport App from './components/App'; \nimport  as serviceWorker from './serviceWorker';</code></pre><p>2. in <strong><strong>App.js:</strong></strong></p><pre><code class=\"language-JS\">import React, { Component } from 'react'; \nimport logo from './logo.svg'; \nimport '../styles/App.css';</code></pre><p>Our directory structure should look like this now:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_Aqgelb3qbhJiESUbGGNUoQ.png\" class=\"kg-image\" alt loading=\"lazy\"></figure><p>We will go ahead now and start building our webpage.</p><p>The first thing in our objectives list is showing a welcome message when the user first opens the webpage. It will show up for 3 seconds, and then changes to another message that will prompt the user to try out the trivia generator.</p><p>Without hooks, this could be done by using React’s lifecycle method <code>componentDidMount</code><em><em> </em></em>which runs right after the component first renders.</p><p>Now, we can use the <a href=\"https://reactjs.org/docs/hooks-effect.html\" rel=\"noopener nofollow\"><em><em>effect hook</em></em></a><em><em> </em></em>instead. It will look something like this:</p><pre><code class=\"language-JS\">useEffect(() =&gt; {\n  //perform something post render\n});</code></pre><p>The function you pass to <code>useEffect</code> will be executed after every render. This combines the lifecycles methods <code>componentDidMount</code><strong><strong> </strong></strong>and <code>componentDidUpdate</code> into one.</p><p>What if you want to do something just after the first time the component renders, like in <code>componentDidMount</code>? You can do this by passing a second parameter to <code>useEffect</code>.</p><p><code>useEffect</code><strong><strong> </strong></strong>accepts an array as a second parameter. This parameter is used as a condition on when to perform the passed function. So, let’s say you want to change a counter only after the variable <strong><strong>counter </strong></strong>changes, you can do it like so:</p><pre><code class=\"language-JS\">useEffect(() =&gt; document.title = `You have clicked ${counter} times`, [counter]);</code></pre><p>This way, the function passed to <code>useEffect</code> will run after render only if the value for <code>counter</code><strong><strong> </strong></strong>changes.</p><p>If we want the function to run only after the first render, we can do that by passing an <strong><strong>empty</strong></strong> array as the second parameter.</p><p>Let’s come back now to what we want to do. We want to show a welcome message when the user first opens the page, then change that message after 3 seconds. We can do that by adding the following inside <strong><strong>App.js</strong></strong>:</p><pre><code class=\"language-JS\">import React, {useEffect} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n   useEffect(() =&gt; {\n     setTimeout(() =&gt; {\n       let welcomeMessage = document.getElementById(\"welcomeMessage\");\n       welcomeMessage.innerHTML = \"Try Out Our Trivia Generator!\";\n     }, 3000);\n   }, []);\n   return (\n     &lt;div className=\"App\"&gt;\n       &lt;header className=\"App-header\"&gt;\n         &lt;h1 id=\"welcomeMessage\"&gt;Welcome to Numbers Trivia!&lt;/h1&gt;\n         &lt;Form /&gt;\n       &lt;/header&gt;\n     &lt;/div&gt;\n   ); }  \nexport default App;</code></pre><p>Here’s what we’re doing:</p><ol><li><strong><strong>Line 1:</strong></strong> We added an import for <code>useEffect</code></li><li><strong><strong>Line 4: </strong></strong>We changed our class component into a function component</li><li><strong><strong>Line 5–10: </strong></strong>we added an effect to our function component. This effect sets a timer after 3 seconds that will change the text in the element with the id <code>welcomeMessage</code><strong><strong>. </strong></strong>Because we passed an <strong><strong>empty</strong></strong> array to <code>useEffect</code>, this effect will only run once.</li><li><strong><strong>Line 11–17: </strong></strong>We replaced the previous code in <strong><strong>App.js </strong></strong>to render an <strong><strong>h1 </strong></strong>element having the id <code>welcomeMessage</code><strong><strong>, </strong></strong>which is our target element.</li></ol><p>Okay, now go to our web page and see the changes. At first, the welcome message “<strong><strong>Welcome to Numbers Trivia!</strong></strong>” will show up, then 3 seconds later it will change into “<strong><strong>Try Out Our Trivia Generator!</strong></strong>” We just used a React Hook!</p><p>Next, let’s create our form input elements. To do that, we will create a new React component called <code>Form</code><strong><strong>. </strong></strong>Create in the directory <strong><strong>components</strong></strong> the file <strong><strong>Form.js. </strong></strong>For now, it will just include the following:</p><pre><code class=\"language-JS\">import React from 'react';  \nfunction Form(props){\n}\nexport default Form;</code></pre><p>This will create the new React component. We’re just importing React, then we’re creating a function called Form. As we said earlier in the tutorial, with the use of hooks we can now create components as stateful functions rather than classes. And in the last line, we’re exporting <strong><strong>Form</strong></strong> in order to import it in other files.</p><p>In the form, we will have a <strong><strong>text </strong></strong>input and <strong><strong>select </strong></strong>elements. This is based on the API we’re using. In the API, two parameters can be sent:</p><ol><li><strong><strong>number: </strong></strong>the number you want to get the trivia for. It can be an <strong><strong>integer</strong></strong>, a date of the form <strong><strong>month/day, </strong></strong>or the keyword <strong><strong>random </strong></strong>which will retrieve facts about a random number.</li><li><strong><strong>type: </strong></strong>the type of information you want to get. There are a few types: <strong><strong>math, date, year, </strong></strong>or, the default, <strong><strong>trivia.</strong></strong></li></ol><p>We will consider the text input element as optional. If the user does not enter a number or a date, we will send the keyword <strong><strong>random</strong></strong> for the number element.</p><p>Let’s add the following code inside the <strong><strong>Form</strong></strong> function in order to render our form:</p><pre><code class=\"language-JS\">function Form(props){\n  return (&lt;form&gt;\n             &lt;div&gt;\n              &lt;input type=\"text\" name=\"number\" placeholder=\"Enter a number (Optional)\" /&gt;\n             &lt;/div&gt;\n             &lt;div&gt;\n              &lt;select name=\"type\"&gt;\n               &lt;option value=\"trivia\"&gt;Trivia&lt;/option&gt;\n               &lt;option value=\"math\"&gt;Math&lt;/option&gt;\n               &lt;option value=\"date\"&gt;Date&lt;/option&gt;\n               &lt;option value=\"year\"&gt;Year&lt;/option&gt;\n              &lt;/select&gt;\n             &lt;/div&gt;\n             &lt;button type=\"submit\"&gt;Generate&lt;/button&gt;\n            &lt;/form&gt;); \n}</code></pre><p>This will create the form with the <strong><strong>text </strong></strong>input and <strong><strong>select </strong></strong>and <strong><strong>button </strong></strong>elements.</p><p>After that, we need to import and render the <strong><strong>Form</strong></strong> component in our <strong><strong>App </strong></strong>component:</p><pre><code class=\"language-JS\">import React, {useEffect} from 'react';\nimport Form from './Form';\nimport '../styles/App.css';  \nfunction App() {\n   useEffect(() =&gt; {\n     setTimeout(() =&gt; {\n       let welcomeMessage = document.getElementById(\"welcomeMessage\");\n       welcomeMessage.innerHTML = \"Try Out Our Trivia Generator!\";\n     }, 3000);\n   }, []);\n   return (\n     &lt;div className=\"App\"&gt;\n       &lt;header className=\"App-header\"&gt;\n         &lt;h1 id=\"welcomeMessage\"&gt;Welcome to Numbers Trivia!&lt;/h1&gt;\n         &lt;Form /&gt;\n       &lt;/header&gt;\n     &lt;/div&gt;\n   );\n }\nexport default App;</code></pre><p>We have changed the imports to import our <code>Form</code><strong><strong> </strong></strong>component, and we added <code>&lt;Form /&gt;</code><strong><strong> </strong></strong>to render the form.</p><p>Let’s also add more styles just to make our form look a little better. Add the following at the end of <strong><strong>App.css</strong></strong>:</p><pre><code class=\"language-CSS\">form {\n   font-size: 15px;\n}  \nform input, form select {\n   padding: 5px;\n}  \nform select {\n   width: 100%; \n}  \nform div {\n   margin-bottom: 8px;\n}</code></pre><p>If you refresh the page now, you will find it has changed and now it’s showing our form.</p><p>Now, we need to add some logic to our form. <strong><strong>On Submit</strong></strong>, we need to get the values of our input elements, then call the API to retrieve the results.</p><p>To handle form elements and their values, you need to use the state of the component. You make the value of the element equal to a property in the state of the component.</p><p>Before hooks, in order to get the value in the state you would have to use <code>this.state.value</code><strong><strong>, </strong></strong>and then to set the state, you will need to call <code>this.setState</code>.</p><p>Now, you can use the state hook. The state hook is the <code>useState</code><strong><strong> </strong></strong>function. It accepts one argument, which is the initial value, and it returns a pair of values: the <strong><strong>current state</strong></strong> and a <strong><strong>function</strong></strong> that updates it. Then, you will be able to access the current state using the first returned value, and update it using the second returned value which is the function.</p><p>Here’s an example:</p><pre><code class=\"language-JS\">const [count, setCount] = useState(0);</code></pre><p>in this example, we call the <code>useState</code><strong><strong> </strong></strong>hook and pass it 0, and we set the returned value equal to <code>count</code> and <code>setCount</code>. This means that we have created state variable called <code>count</code>. Its initial value is 0, and to change its value we can use <code>setCount</code>.</p><p>For our <code>Form</code><strong><strong> </strong></strong>component, we need two state variables, one for the text<strong><strong> </strong></strong>input which we will call <code>number</code>, and one for the select<strong><strong> </strong></strong>input which we will call <code>type</code>. Then, on change event for these two input elements, we will change the values for <code>number</code><strong><strong> </strong></strong>and <code>type</code> using the function returned by <code>setState</code><strong><strong>.</strong></strong></p><p>Open our <code>Form</code><strong><strong> </strong></strong>component and change it to the following:</p><pre><code class=\"language-JS\">import React, { useState } from 'react';\nfunction Form(props){\n  let [number, setNumber] = useState(\"random\");\n  let [type, setType] = useState(\"trivia\");\n  function onNumberChanged(e){\n    let value = e.target.value.trim();\n    if(!value.length){\n      setNumber(\"random\"); //default value\n    } else {\n      setNumber(value);\n    }\n  }\n  function onTypeChanged(e){\n    let value = e.target.value.trim();\n    if(!value.length){\n      setType(\"trivia\"); //default value\n    } else {\n      setType(value);\n    }\n  }\n  return (&lt;form&gt;\n            &lt;div&gt;\n              &lt;input type=\"text\" name=\"number\" placeholder=\"Enter a number (Optional)\" value={number} onChange={onNumberChanged} /&gt;\n            &lt;/div&gt;\n            &lt;div&gt;\n              &lt;select name=\"type\" value={type} onChange={onTypeChanged}&gt;\n                &lt;option value=\"trivia\"&gt;Trivia&lt;/option&gt;\n                &lt;option value=\"math\"&gt;Math&lt;/option&gt;\n                &lt;option value=\"date\"&gt;Date&lt;/option&gt;\n                &lt;option value=\"year\"&gt;Year&lt;/option&gt;\n              &lt;/select&gt;\n            &lt;/div&gt;\n            &lt;button type=\"submit\"&gt;Generate&lt;/button&gt;\n&lt;/form&gt;);\n}\nexport default Form;</code></pre><ol><li><strong><strong>Line 1: </strong></strong>add an import for <code>useState</code> hook.</li><li><strong><strong>Line 3–4: </strong></strong>create two state variables <code>number</code> and <code>type</code> using <code>useState</code> . Here we pass <strong><strong>random </strong></strong>as the initial value for number, and <strong><strong>trivia </strong></strong>as initial value for type because they are the default values for the parameters in the API.</li><li><strong><strong>Line 5–10: </strong></strong>implement input change handler functions for both text and select inputs, where we change the value of the state variables using the functions returned by <code>useState</code> . If the value is unset, we automatically change the values to the default value.</li><li><strong><strong>Line 13: </strong></strong>pass the <code>onNumberChanged</code> function to <code>onChange</code> event for text input.</li><li><strong><strong>Line 16: </strong></strong>pass the <code>onTypeChanged</code> function to <code>onChange</code> event for select input.</li></ol><p>In addition, let’s go back to our <code>App</code> component to modify it and use states. Instead of modifying our welcome message by changing the <code>innerHTML</code> of the element, we will use a state. Our App component should now be like this:</p><pre><code>import React, {useEffect, useState} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n  const [ welcomeMessage, setWelcomeMessage ] = useState(\n    \"Welcome to Numbers Trivia!\",\n  );\nuseEffect(() =&gt; {\n    setTimeout(() =&gt; {\n      setWelcomeMessage(\"Try Out Our Trivia Generator!\");\n    }, 3000);\n  }, []);\nreturn (\n    &lt;div className=\"App\"&gt;\n      &lt;header className=\"App-header\"&gt;\n        &lt;h1&gt;{welcomeMessage}&lt;/h1&gt;\n      &lt;/header&gt;\n      &lt;Form/&gt;\n    &lt;/div&gt;\n  );\n}\nexport default App;</code></pre><p>Now, we are using <code>useState</code> to declare and initialize our welcome message. It will return <code>welcomeMessage</code> , our state variable, and <code>setWelcomeMessage</code> , which we will use to change the value of <code>welcomeMessage</code> after 3 seconds from “<strong><strong>Welcome to Numbers Trivia!</strong></strong>” to “<strong><strong>Try Out Our Trivia Generator!</strong></strong>”</p><p>What’s left now is to add a function to handle the form’s <code>onSubmit</code> event. On submit, we will send a request to the API with our parameters, then display the result.</p><p>In order to perform the request, we need to install <a href=\"https://github.com/axios/axios\" rel=\"noopener nofollow\">axios</a>:</p><pre><code class=\"language-Shell\">npm i axios</code></pre><p>Then, require axios at the beginning of <strong><strong>Form.js:</strong></strong></p><pre><code class=\"language-JS\">const axios = require('axios');</code></pre><p>Now, add the following function below <code>onTypeChanged</code> in our <strong><strong>Form</strong></strong> component:</p><pre><code class=\"language-JS\">function onSubmit(e){\n  e.preventDefault();\n  axios.get('http://numbersapi.com/' + number + '/' + type)\n       .then(function(response){\n         let elm = document.getElementById('result');\n         elm.innerHTML = response.data;\n       }).catch(function(e){\n         console.log(\"error\", e); //simple error handling\n       });\n}</code></pre><p>We’re just performing a request to the API, passing the <code>number</code> and <code>type</code> then displaying the result in an element of id <code>result</code> (which we will add in a minute). In case of an error, we’re just displaying it in the console just as a simple error handling.</p><p>Now, let’s add this function as the handler for the form <code>onSubmit</code> event in the return statement in Form.js:</p><pre><code class=\"language-JSX\">&lt;form onSubmit={onSubmit}&gt;</code></pre><p>The only thing left is to add the <code>#result</code> element. We can add it in <strong><strong>App.js </strong></strong>before <code>&lt;Form /&gt;</code> :</p><pre><code class=\"language-JSX\">&lt;div id=\"result\" style={{marginBottom: '15px'}}&gt;&lt;/div&gt;</code></pre><p>Alright, now go to your website and discover all new trivia about numbers!</p><hr><h2 id=\"conclusion\">Conclusion</h2><p>You just created a React app and used some React Hooks! Of course, there’s still more to explore and learn, so be sure to head to the <a href=\"https://reactjs.org/docs/hooks-intro.html\" rel=\"noopener nofollow\">docs</a> to learn more about React Hooks.</p>","url":"https://backend.shahednasser.com/react-hooks-tutorial-create-a-number-trivia-generator-website/","canonical_url":null,"uuid":"033786bf-592f-454b-b640-42920b676fb8","codeinjection_foot":null,"codeinjection_head":null,"codeinjection_styles":null,"comment_id":"5faa42902280bc001e2ccc95","reading_time":11,"send_email_when_published":null,"email_subject":null,"childHtmlRehype":{"html":"<p>Hooks have been officially added to React as of React 16.8. One of the main benefits of Hooks in React is that you can use state and effect (which is generally a combination of different life cycles into one) in a component without creating a class.</p><p>In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that gives the user some options to pick from in order to generate some random number trivia.</p><p>You can check out the demo for the website <a href=\"http://numbers-trivia.surge.sh/\" rel=\"noopener nofollow\">here</a>, and the source code on the <a href=\"https://github.com/shahednasser/numbers-trivia\" rel=\"noopener nofollow\">GitHub repository</a>.</p><p>Let’s first start by creating a react app. Since our website will be very simple, we will use the <code class=\"language-text\">create-react-app</code> command. If you don’t have it installed, you can install it using <code class=\"language-text\">npm</code><strong><strong>.</strong></strong></p><p>Run the following in your terminal or CMD:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"shell\"><pre class=\"language-shell\"><code class=\"language-shell\"><span class=\"token function\">npm</span> i -g create-react-app</code></pre></div><p>This will install <code class=\"language-text\">create-react-app</code> globally.</p><p>Now we can create our React app:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"shell\"><pre class=\"language-shell\"><code class=\"language-shell\">create-react-app numbers-trivia</code></pre></div><p>Running this command will create a directory in the working directory with the name you supply for the React app. I named it <strong><strong>numbers-trivia</strong></strong> but you can call it whatever you want.</p><p>Inside that directory, it will also install all the packages and files needed to run the website. It will install packages like <strong><strong>react</strong></strong>, <strong><strong>react-dom</strong></strong>, <strong><strong>react-scripts</strong></strong> and more.</p><p>Once it’s done, change into the newly created directory and start the server:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"shell\"><pre class=\"language-shell\"><code class=\"language-shell\"><span class=\"token builtin class-name\">cd</span> numbers-trivia\n<span class=\"token function\">npm</span> start</code></pre></div><p>Once you start the server, a web page of your website in your favorite browser will open. You will see a page with just the logo and a link to learn React.</p><p>Before we start changing the page, if you are not familiar with React, let’s take a look at the structure of our React app. It should look something like this:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_R1irPlPj9UsboCM_KI5CgA.png\" class=\"kg-image\" alt=\"\" loading=\"lazy\"></figure><p>In our root directory, we will find a bunch of directories. <strong><strong>node_modules </strong></strong>holds all the packages React needs to run and any package you might add. <strong><strong>public </strong></strong>holds the files our server serves.</p><p>The directory that we will spend most of our time in is the <strong><strong>src</strong></strong> directory. This directory will hold all of our React components.</p><p>As you can see there are a bunch of files in that directory. <strong><strong>index.js</strong></strong> is basically the file that renders our highest React component.</p><p>We only have one React component right now which is in <strong><strong>App.js. </strong></strong>If you open it, you will find the code that renders the logo with the link to learn React that you currently see on the website.</p><p>So, in order to see how changing our App component will change the content of the website, let’s modify the code by removing the current content and replacing it with our favorite phrase: “Hello, World!”</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> Component <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span> \n<span class=\"token keyword\">import</span> logo <span class=\"token keyword\">from</span> <span class=\"token string\">'./logo.svg'</span> \n<span class=\"token keyword\">import</span> <span class=\"token string\">'./App.css'</span>  \n<span class=\"token keyword\">class</span> <span class=\"token class-name\">App</span> <span class=\"token keyword\">extends</span> <span class=\"token class-name\">Component</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token function\">render</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n       <span class=\"token operator\">&#x3C;</span>div className<span class=\"token operator\">=</span><span class=\"token string\">\"App\"</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>header className<span class=\"token operator\">=</span><span class=\"token string\">\"App-header\"</span><span class=\"token operator\">></span>\n           <span class=\"token operator\">&#x3C;</span>h1<span class=\"token operator\">></span>Hello<span class=\"token punctuation\">,</span> World<span class=\"token operator\">!</span><span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>h1<span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>header<span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n     <span class=\"token punctuation\">)</span>\n   <span class=\"token punctuation\">}</span>\n <span class=\"token punctuation\">}</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> App</code></pre></div><p>We just replaced the content of the <strong><strong>header</strong></strong> element. Now, if your server is still running you will see that your page updated without you refreshing it, and you will see that the previous content is replaced with <strong><strong>Hello, World!</strong></strong></p><p>So now we know how and where we should edit our React components in order to get the result we want. We can go ahead and start with our objective.</p><p>What we’ll do for this website is the following:</p><ol><li>Show a welcome message the first time the user opens the website, then replace it with a message prompting the user to try the generator.</li><li>Render a form with <strong><strong>text </strong></strong>and <strong><strong>select</strong></strong> inputs. The <strong><strong>text </strong></strong>input is where the user can enter the number they want to see trivia about, and the <strong><strong>select </strong></strong>input will provide the user with options related to the trivia.</li><li>On submitting the form, send a request to <a href=\"http://numbersapi.com/\" rel=\"noopener nofollow\">this API</a> to fetch the trivia we need.</li><li>Render the trivia for the user to see it.</li></ol><p>Let’s start by organizing our directory structure first. In React it’s good practice to create a directory inside <strong><strong>src</strong></strong> holding all the components. We’ll create a directory called <strong><strong>components</strong></strong>. Once you create the directory, move <strong><strong>App.js</strong></strong> into there. We will also create a directory called <strong><strong>styles</strong></strong> and move <strong><strong>App.css </strong></strong>and <strong><strong>index.css </strong></strong>into it.</p><p>When you do that, you will need to change the imports in your files as following:</p><ol><li>in <strong><strong>index.js:</strong></strong></li></ol><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> ReactDOM <span class=\"token keyword\">from</span> <span class=\"token string\">'react-dom'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> <span class=\"token string\">'../styles/index.css'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> App <span class=\"token keyword\">from</span> <span class=\"token string\">'./components/App'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span>  <span class=\"token keyword\">as</span> serviceWorker <span class=\"token keyword\">from</span> <span class=\"token string\">'./serviceWorker'</span><span class=\"token punctuation\">;</span></code></pre></div><p>2. in <strong><strong>App.js:</strong></strong></p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> Component <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> logo <span class=\"token keyword\">from</span> <span class=\"token string\">'./logo.svg'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> <span class=\"token string\">'../styles/App.css'</span><span class=\"token punctuation\">;</span></code></pre></div><p>Our directory structure should look like this now:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_Aqgelb3qbhJiESUbGGNUoQ.png\" class=\"kg-image\" alt=\"\" loading=\"lazy\"></figure><p>We will go ahead now and start building our webpage.</p><p>The first thing in our objectives list is showing a welcome message when the user first opens the webpage. It will show up for 3 seconds, and then changes to another message that will prompt the user to try out the trivia generator.</p><p>Without hooks, this could be done by using React’s lifecycle method <code class=\"language-text\">componentDidMount</code><em><em> </em></em>which runs right after the component first renders.</p><p>Now, we can use the <a href=\"https://reactjs.org/docs/hooks-effect.html\" rel=\"noopener nofollow\"><em><em>effect hook</em></em></a><em><em> </em></em>instead. It will look something like this:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">//perform something post render</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div><p>The function you pass to <code class=\"language-text\">useEffect</code> will be executed after every render. This combines the lifecycles methods <code class=\"language-text\">componentDidMount</code><strong><strong> </strong></strong>and <code class=\"language-text\">componentDidUpdate</code> into one.</p><p>What if you want to do something just after the first time the component renders, like in <code class=\"language-text\">componentDidMount</code>? You can do this by passing a second parameter to <code class=\"language-text\">useEffect</code>.</p><p><code class=\"language-text\">useEffect</code><strong><strong> </strong></strong>accepts an array as a second parameter. This parameter is used as a condition on when to perform the passed function. So, let’s say you want to change a counter only after the variable <strong><strong>counter </strong></strong>changes, you can do it like so:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> document<span class=\"token punctuation\">.</span>title <span class=\"token operator\">=</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">You have clicked </span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>counter<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token string\"> times</span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span>counter<span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div><p>This way, the function passed to <code class=\"language-text\">useEffect</code> will run after render only if the value for <code class=\"language-text\">counter</code><strong><strong> </strong></strong>changes.</p><p>If we want the function to run only after the first render, we can do that by passing an <strong><strong>empty</strong></strong> array as the second parameter.</p><p>Let’s come back now to what we want to do. We want to show a welcome message when the user first opens the page, then change that message after 3 seconds. We can do that by adding the following inside <strong><strong>App.js</strong></strong>:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>useEffect<span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> Form <span class=\"token keyword\">from</span> <span class=\"token string\">'./Form'</span><span class=\"token punctuation\">;</span> \n<span class=\"token keyword\">import</span> <span class=\"token string\">'../styles/App.css'</span><span class=\"token punctuation\">;</span> \n \n<span class=\"token keyword\">function</span> <span class=\"token function\">App</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token function\">setTimeout</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">let</span> welcomeMessage <span class=\"token operator\">=</span> document<span class=\"token punctuation\">.</span><span class=\"token function\">getElementById</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"welcomeMessage\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       welcomeMessage<span class=\"token punctuation\">.</span>innerHTML <span class=\"token operator\">=</span> <span class=\"token string\">\"Try Out Our Trivia Generator!\"</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token number\">3000</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n     <span class=\"token operator\">&#x3C;</span>div className<span class=\"token operator\">=</span><span class=\"token string\">\"App\"</span><span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span>header className<span class=\"token operator\">=</span><span class=\"token string\">\"App-header\"</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>h1 id<span class=\"token operator\">=</span><span class=\"token string\">\"welcomeMessage\"</span><span class=\"token operator\">></span>Welcome to Numbers Trivia<span class=\"token operator\">!</span><span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>h1<span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>Form <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>header<span class=\"token operator\">></span>\n     <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n   <span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token punctuation\">}</span>  \n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> App<span class=\"token punctuation\">;</span></code></pre></div><p>Here’s what we’re doing:</p><ol><li><strong><strong>Line 1:</strong></strong> We added an import for <code class=\"language-text\">useEffect</code></li><li><strong><strong>Line 4: </strong></strong>We changed our class component into a function component</li><li><strong><strong>Line 5–10: </strong></strong>we added an effect to our function component. This effect sets a timer after 3 seconds that will change the text in the element with the id <code class=\"language-text\">welcomeMessage</code><strong><strong>. </strong></strong>Because we passed an <strong><strong>empty</strong></strong> array to <code class=\"language-text\">useEffect</code>, this effect will only run once.</li><li><strong><strong>Line 11–17: </strong></strong>We replaced the previous code in <strong><strong>App.js </strong></strong>to render an <strong><strong>h1 </strong></strong>element having the id <code class=\"language-text\">welcomeMessage</code><strong><strong>, </strong></strong>which is our target element.</li></ol><p>Okay, now go to our web page and see the changes. At first, the welcome message “<strong><strong>Welcome to Numbers Trivia!</strong></strong>” will show up, then 3 seconds later it will change into “<strong><strong>Try Out Our Trivia Generator!</strong></strong>” We just used a React Hook!</p><p>Next, let’s create our form input elements. To do that, we will create a new React component called <code class=\"language-text\">Form</code><strong><strong>. </strong></strong>Create in the directory <strong><strong>components</strong></strong> the file <strong><strong>Form.js. </strong></strong>For now, it will just include the following:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span>  \n<span class=\"token keyword\">function</span> <span class=\"token function\">Form</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">props</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n<span class=\"token punctuation\">}</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> Form<span class=\"token punctuation\">;</span></code></pre></div><p>This will create the new React component. We’re just importing React, then we’re creating a function called Form. As we said earlier in the tutorial, with the use of hooks we can now create components as stateful functions rather than classes. And in the last line, we’re exporting <strong><strong>Form</strong></strong> in order to import it in other files.</p><p>In the form, we will have a <strong><strong>text </strong></strong>input and <strong><strong>select </strong></strong>elements. This is based on the API we’re using. In the API, two parameters can be sent:</p><ol><li><strong><strong>number: </strong></strong>the number you want to get the trivia for. It can be an <strong><strong>integer</strong></strong>, a date of the form <strong><strong>month/day, </strong></strong>or the keyword <strong><strong>random </strong></strong>which will retrieve facts about a random number.</li><li><strong><strong>type: </strong></strong>the type of information you want to get. There are a few types: <strong><strong>math, date, year, </strong></strong>or, the default, <strong><strong>trivia.</strong></strong></li></ol><p>We will consider the text input element as optional. If the user does not enter a number or a date, we will send the keyword <strong><strong>random</strong></strong> for the number element.</p><p>Let’s add the following code inside the <strong><strong>Form</strong></strong> function in order to render our form:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">Form</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">props</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">&#x3C;</span>form<span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span>div<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span>input type<span class=\"token operator\">=</span><span class=\"token string\">\"text\"</span> name<span class=\"token operator\">=</span><span class=\"token string\">\"number\"</span> placeholder<span class=\"token operator\">=</span><span class=\"token string\">\"Enter a number (Optional)\"</span> <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span>div<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span>select name<span class=\"token operator\">=</span><span class=\"token string\">\"type\"</span><span class=\"token operator\">></span>\n               <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"trivia\"</span><span class=\"token operator\">></span>Trivia<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n               <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"math\"</span><span class=\"token operator\">></span>Math<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n               <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"date\"</span><span class=\"token operator\">></span>Date<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n               <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"year\"</span><span class=\"token operator\">></span>Year<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>select<span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n             <span class=\"token operator\">&#x3C;</span>button type<span class=\"token operator\">=</span><span class=\"token string\">\"submit\"</span><span class=\"token operator\">></span>Generate<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>button<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>form<span class=\"token operator\">></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> \n<span class=\"token punctuation\">}</span></code></pre></div><p>This will create the form with the <strong><strong>text </strong></strong>input and <strong><strong>select </strong></strong>and <strong><strong>button </strong></strong>elements.</p><p>After that, we need to import and render the <strong><strong>Form</strong></strong> component in our <strong><strong>App </strong></strong>component:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>useEffect<span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> Form <span class=\"token keyword\">from</span> <span class=\"token string\">'./Form'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> <span class=\"token string\">'../styles/App.css'</span><span class=\"token punctuation\">;</span>  \n<span class=\"token keyword\">function</span> <span class=\"token function\">App</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token function\">setTimeout</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">let</span> welcomeMessage <span class=\"token operator\">=</span> document<span class=\"token punctuation\">.</span><span class=\"token function\">getElementById</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"welcomeMessage\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       welcomeMessage<span class=\"token punctuation\">.</span>innerHTML <span class=\"token operator\">=</span> <span class=\"token string\">\"Try Out Our Trivia Generator!\"</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token number\">3000</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n     <span class=\"token operator\">&#x3C;</span>div className<span class=\"token operator\">=</span><span class=\"token string\">\"App\"</span><span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span>header className<span class=\"token operator\">=</span><span class=\"token string\">\"App-header\"</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>h1 id<span class=\"token operator\">=</span><span class=\"token string\">\"welcomeMessage\"</span><span class=\"token operator\">></span>Welcome to Numbers Trivia<span class=\"token operator\">!</span><span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>h1<span class=\"token operator\">></span>\n         <span class=\"token operator\">&#x3C;</span>Form <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n       <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>header<span class=\"token operator\">></span>\n     <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n   <span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n <span class=\"token punctuation\">}</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> App<span class=\"token punctuation\">;</span></code></pre></div><p>We have changed the imports to import our <code class=\"language-text\">Form</code><strong><strong> </strong></strong>component, and we added <code class=\"language-text\">&#x3C;Form /></code><strong><strong> </strong></strong>to render the form.</p><p>Let’s also add more styles just to make our form look a little better. Add the following at the end of <strong><strong>App.css</strong></strong>:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">form</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token property\">font-size</span><span class=\"token punctuation\">:</span> 15px<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>  \n<span class=\"token selector\">form input, form select</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token property\">padding</span><span class=\"token punctuation\">:</span> 5px<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>  \n<span class=\"token selector\">form select</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token property\">width</span><span class=\"token punctuation\">:</span> 100%<span class=\"token punctuation\">;</span> \n<span class=\"token punctuation\">}</span>  \n<span class=\"token selector\">form div</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token property\">margin-bottom</span><span class=\"token punctuation\">:</span> 8px<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>If you refresh the page now, you will find it has changed and now it’s showing our form.</p><p>Now, we need to add some logic to our form. <strong><strong>On Submit</strong></strong>, we need to get the values of our input elements, then call the API to retrieve the results.</p><p>To handle form elements and their values, you need to use the state of the component. You make the value of the element equal to a property in the state of the component.</p><p>Before hooks, in order to get the value in the state you would have to use <code class=\"language-text\">this.state.value</code><strong><strong>, </strong></strong>and then to set the state, you will need to call <code class=\"language-text\">this.setState</code>.</p><p>Now, you can use the state hook. The state hook is the <code class=\"language-text\">useState</code><strong><strong> </strong></strong>function. It accepts one argument, which is the initial value, and it returns a pair of values: the <strong><strong>current state</strong></strong> and a <strong><strong>function</strong></strong> that updates it. Then, you will be able to access the current state using the first returned value, and update it using the second returned value which is the function.</p><p>Here’s an example:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">const</span> <span class=\"token punctuation\">[</span>count<span class=\"token punctuation\">,</span> setCount<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token number\">0</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div><p>in this example, we call the <code class=\"language-text\">useState</code><strong><strong> </strong></strong>hook and pass it 0, and we set the returned value equal to <code class=\"language-text\">count</code> and <code class=\"language-text\">setCount</code>. This means that we have created state variable called <code class=\"language-text\">count</code>. Its initial value is 0, and to change its value we can use <code class=\"language-text\">setCount</code>.</p><p>For our <code class=\"language-text\">Form</code><strong><strong> </strong></strong>component, we need two state variables, one for the text<strong><strong> </strong></strong>input which we will call <code class=\"language-text\">number</code>, and one for the select<strong><strong> </strong></strong>input which we will call <code class=\"language-text\">type</code>. Then, on change event for these two input elements, we will change the values for <code class=\"language-text\">number</code><strong><strong> </strong></strong>and <code class=\"language-text\">type</code> using the function returned by <code class=\"language-text\">setState</code><strong><strong>.</strong></strong></p><p>Open our <code class=\"language-text\">Form</code><strong><strong> </strong></strong>component and change it to the following:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> useState <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">function</span> <span class=\"token function\">Form</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">props</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">let</span> <span class=\"token punctuation\">[</span>number<span class=\"token punctuation\">,</span> setNumber<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"random\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token keyword\">let</span> <span class=\"token punctuation\">[</span>type<span class=\"token punctuation\">,</span> setType<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"trivia\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token keyword\">function</span> <span class=\"token function\">onNumberChanged</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">e</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">let</span> value <span class=\"token operator\">=</span> e<span class=\"token punctuation\">.</span>target<span class=\"token punctuation\">.</span>value<span class=\"token punctuation\">.</span><span class=\"token function\">trim</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token keyword\">if</span><span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>value<span class=\"token punctuation\">.</span>length<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setNumber</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"random\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">//default value</span>\n    <span class=\"token punctuation\">}</span> <span class=\"token keyword\">else</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setNumber</span><span class=\"token punctuation\">(</span>value<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword\">function</span> <span class=\"token function\">onTypeChanged</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">e</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">let</span> value <span class=\"token operator\">=</span> e<span class=\"token punctuation\">.</span>target<span class=\"token punctuation\">.</span>value<span class=\"token punctuation\">.</span><span class=\"token function\">trim</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token keyword\">if</span><span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>value<span class=\"token punctuation\">.</span>length<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setType</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"trivia\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">//default value</span>\n    <span class=\"token punctuation\">}</span> <span class=\"token keyword\">else</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setType</span><span class=\"token punctuation\">(</span>value<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">&#x3C;</span>form<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span>div<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span>input type<span class=\"token operator\">=</span><span class=\"token string\">\"text\"</span> name<span class=\"token operator\">=</span><span class=\"token string\">\"number\"</span> placeholder<span class=\"token operator\">=</span><span class=\"token string\">\"Enter a number (Optional)\"</span> value<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>number<span class=\"token punctuation\">}</span> onChange<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>onNumberChanged<span class=\"token punctuation\">}</span> <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span>div<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span>select name<span class=\"token operator\">=</span><span class=\"token string\">\"type\"</span> value<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>type<span class=\"token punctuation\">}</span> onChange<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>onTypeChanged<span class=\"token punctuation\">}</span><span class=\"token operator\">></span>\n                <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"trivia\"</span><span class=\"token operator\">></span>Trivia<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n                <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"math\"</span><span class=\"token operator\">></span>Math<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n                <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"date\"</span><span class=\"token operator\">></span>Date<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n                <span class=\"token operator\">&#x3C;</span>option value<span class=\"token operator\">=</span><span class=\"token string\">\"year\"</span><span class=\"token operator\">></span>Year<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>option<span class=\"token operator\">></span>\n              <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>select<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n            <span class=\"token operator\">&#x3C;</span>button type<span class=\"token operator\">=</span><span class=\"token string\">\"submit\"</span><span class=\"token operator\">></span>Generate<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>button<span class=\"token operator\">></span>\n<span class=\"token operator\">&#x3C;</span><span class=\"token operator\">/</span>form<span class=\"token operator\">></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> Form<span class=\"token punctuation\">;</span></code></pre></div><ol><li><strong><strong>Line 1: </strong></strong>add an import for <code class=\"language-text\">useState</code> hook.</li><li><strong><strong>Line 3–4: </strong></strong>create two state variables <code class=\"language-text\">number</code> and <code class=\"language-text\">type</code> using <code class=\"language-text\">useState</code> . Here we pass <strong><strong>random </strong></strong>as the initial value for number, and <strong><strong>trivia </strong></strong>as initial value for type because they are the default values for the parameters in the API.</li><li><strong><strong>Line 5–10: </strong></strong>implement input change handler functions for both text and select inputs, where we change the value of the state variables using the functions returned by <code class=\"language-text\">useState</code> . If the value is unset, we automatically change the values to the default value.</li><li><strong><strong>Line 13: </strong></strong>pass the <code class=\"language-text\">onNumberChanged</code> function to <code class=\"language-text\">onChange</code> event for text input.</li><li><strong><strong>Line 16: </strong></strong>pass the <code class=\"language-text\">onTypeChanged</code> function to <code class=\"language-text\">onChange</code> event for select input.</li></ol><p>In addition, let’s go back to our <code class=\"language-text\">App</code> component to modify it and use states. Instead of modifying our welcome message by changing the <code class=\"language-text\">innerHTML</code> of the element, we will use a state. Our App component should now be like this:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">import React, {useEffect, useState} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n  const [ welcomeMessage, setWelcomeMessage ] = useState(\n    \"Welcome to Numbers Trivia!\",\n  );\nuseEffect(() => {\n    setTimeout(() => {\n      setWelcomeMessage(\"Try Out Our Trivia Generator!\");\n    }, 3000);\n  }, []);\nreturn (\n    &#x3C;div className=\"App\">\n      &#x3C;header className=\"App-header\">\n        &#x3C;h1>{welcomeMessage}&#x3C;/h1>\n      &#x3C;/header>\n      &#x3C;Form/>\n    &#x3C;/div>\n  );\n}\nexport default App;</code></pre></div><p>Now, we are using <code class=\"language-text\">useState</code> to declare and initialize our welcome message. It will return <code class=\"language-text\">welcomeMessage</code> , our state variable, and <code class=\"language-text\">setWelcomeMessage</code> , which we will use to change the value of <code class=\"language-text\">welcomeMessage</code> after 3 seconds from “<strong><strong>Welcome to Numbers Trivia!</strong></strong>” to “<strong><strong>Try Out Our Trivia Generator!</strong></strong>”</p><p>What’s left now is to add a function to handle the form’s <code class=\"language-text\">onSubmit</code> event. On submit, we will send a request to the API with our parameters, then display the result.</p><p>In order to perform the request, we need to install <a href=\"https://github.com/axios/axios\" rel=\"noopener nofollow\">axios</a>:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"shell\"><pre class=\"language-shell\"><code class=\"language-shell\"><span class=\"token function\">npm</span> i axios</code></pre></div><p>Then, require axios at the beginning of <strong><strong>Form.js:</strong></strong></p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">const</span> axios <span class=\"token operator\">=</span> <span class=\"token function\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'axios'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div><p>Now, add the following function below <code class=\"language-text\">onTypeChanged</code> in our <strong><strong>Form</strong></strong> component:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">onSubmit</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">e</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n  e<span class=\"token punctuation\">.</span><span class=\"token function\">preventDefault</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  axios<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'http://numbersapi.com/'</span> <span class=\"token operator\">+</span> number <span class=\"token operator\">+</span> <span class=\"token string\">'/'</span> <span class=\"token operator\">+</span> type<span class=\"token punctuation\">)</span>\n       <span class=\"token punctuation\">.</span><span class=\"token function\">then</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">function</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">response</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n         <span class=\"token keyword\">let</span> elm <span class=\"token operator\">=</span> document<span class=\"token punctuation\">.</span><span class=\"token function\">getElementById</span><span class=\"token punctuation\">(</span><span class=\"token string\">'result'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         elm<span class=\"token punctuation\">.</span>innerHTML <span class=\"token operator\">=</span> response<span class=\"token punctuation\">.</span>data<span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">catch</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">function</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">e</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n         console<span class=\"token punctuation\">.</span><span class=\"token function\">log</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"error\"</span><span class=\"token punctuation\">,</span> e<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">//simple error handling</span>\n       <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>We’re just performing a request to the API, passing the <code class=\"language-text\">number</code> and <code class=\"language-text\">type</code> then displaying the result in an element of id <code class=\"language-text\">result</code> (which we will add in a minute). In case of an error, we’re just displaying it in the console just as a simple error handling.</p><p>Now, let’s add this function as the handler for the form <code class=\"language-text\">onSubmit</code> event in the return statement in Form.js:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"jsx\"><pre class=\"language-jsx\"><code class=\"language-jsx\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;</span>form</span> <span class=\"token attr-name\">onSubmit</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>onSubmit<span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span></code></pre></div><p>The only thing left is to add the <code class=\"language-text\">#result</code> element. We can add it in <strong><strong>App.js </strong></strong>before <code class=\"language-text\">&#x3C;Form /></code> :</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"jsx\"><pre class=\"language-jsx\"><code class=\"language-jsx\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;</span>div</span> <span class=\"token attr-name\">id</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>result<span class=\"token punctuation\">\"</span></span> <span class=\"token attr-name\">style</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token punctuation\">{</span><span class=\"token literal-property property\">marginBottom</span><span class=\"token operator\">:</span> <span class=\"token string\">'15px'</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;/</span>div</span><span class=\"token punctuation\">></span></span></code></pre></div><p>Alright, now go to your website and discover all new trivia about numbers!</p><hr><h2 id=\"conclusion\">Conclusion</h2><p>You just created a React app and used some React Hooks! Of course, there’s still more to explore and learn, so be sure to head to the <a href=\"https://reactjs.org/docs/hooks-intro.html\" rel=\"noopener nofollow\">docs</a> to learn more about React Hooks.</p>","htmlAst":{"type":"root","children":[{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Hooks have been officially added to React as of React 16.8. One of the main benefits of Hooks in React is that you can use state and effect (which is generally a combination of different life cycles into one) in a component without creating a class."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In this tutorial, you’ll learn how to exactly use hooks in React. We will build a simple website that gives the user some options to pick from in order to generate some random number trivia."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"You can check out the demo for the website "},{"type":"element","tagName":"a","properties":{"href":"http://numbers-trivia.surge.sh/","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"here"}]},{"type":"text","value":", and the source code on the "},{"type":"element","tagName":"a","properties":{"href":"https://github.com/shahednasser/numbers-trivia","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"GitHub repository"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s first start by creating a react app. Since our website will be very simple, we will use the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"create-react-app"}]},{"type":"text","value":" command. If you don’t have it installed, you can install it using "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"npm"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"."}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Run the following in your terminal or CMD:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"shell"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"npm"}]},{"type":"text","value":" i -g create-react-app"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This will install "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"create-react-app"}]},{"type":"text","value":" globally."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now we can create our React app:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"shell"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-shell"]},"children":[{"type":"text","value":"create-react-app numbers-trivia"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Running this command will create a directory in the working directory with the name you supply for the React app. I named it "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"numbers-trivia"}]}]},{"type":"text","value":" but you can call it whatever you want."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Inside that directory, it will also install all the packages and files needed to run the website. It will install packages like "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"react"}]}]},{"type":"text","value":", "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"react-dom"}]}]},{"type":"text","value":", "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"react-scripts"}]}]},{"type":"text","value":" and more."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Once it’s done, change into the newly created directory and start the server:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"shell"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","builtin","class-name"]},"children":[{"type":"text","value":"cd"}]},{"type":"text","value":" numbers-trivia\n"},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"npm"}]},{"type":"text","value":" start"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Once you start the server, a web page of your website in your favorite browser will open. You will see a page with just the logo and a link to learn React."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Before we start changing the page, if you are not familiar with React, let’s take a look at the structure of our React app. It should look something like this:"}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-image-card"]},"children":[{"type":"element","tagName":"img","properties":{"src":"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_R1irPlPj9UsboCM_KI5CgA.png","className":["kg-image"],"alt":"","loading":"lazy"},"children":[]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In our root directory, we will find a bunch of directories. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"node_modules "}]}]},{"type":"text","value":"holds all the packages React needs to run and any package you might add. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"public "}]}]},{"type":"text","value":"holds the files our server serves."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The directory that we will spend most of our time in is the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"src"}]}]},{"type":"text","value":" directory. This directory will hold all of our React components."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"As you can see there are a bunch of files in that directory. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index.js"}]}]},{"type":"text","value":" is basically the file that renders our highest React component."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We only have one React component right now which is in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js. "}]}]},{"type":"text","value":"If you open it, you will find the code that renders the logo with the link to learn React that you currently see on the website."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"So, in order to see how changing our App component will change the content of the website, let’s modify the code by removing the current content and replacing it with our favorite phrase: “Hello, World!”"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":" Component "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" logo "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./logo.svg'"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./App.css'"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"class"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","class-name"]},"children":[{"type":"text","value":"App"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"extends"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","class-name"]},"children":[{"type":"text","value":"Component"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"render"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"header className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App-header\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n           "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"h1"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Hello"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" World"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"h1"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"header"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" App"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We just replaced the content of the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"header"}]}]},{"type":"text","value":" element. Now, if your server is still running you will see that your page updated without you refreshing it, and you will see that the previous content is replaced with "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Hello, World!"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"So now we know how and where we should edit our React components in order to get the result we want. We can go ahead and start with our objective."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What we’ll do for this website is the following:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Show a welcome message the first time the user opens the website, then replace it with a message prompting the user to try the generator."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Render a form with "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"text "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"select"}]}]},{"type":"text","value":" inputs. The "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"text "}]}]},{"type":"text","value":"input is where the user can enter the number they want to see trivia about, and the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"select "}]}]},{"type":"text","value":"input will provide the user with options related to the trivia."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"On submitting the form, send a request to "},{"type":"element","tagName":"a","properties":{"href":"http://numbersapi.com/","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"this API"}]},{"type":"text","value":" to fetch the trivia we need."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Render the trivia for the user to see it."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s start by organizing our directory structure first. In React it’s good practice to create a directory inside "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"src"}]}]},{"type":"text","value":" holding all the components. We’ll create a directory called "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"components"}]}]},{"type":"text","value":". Once you create the directory, move "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js"}]}]},{"type":"text","value":" into there. We will also create a directory called "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"styles"}]}]},{"type":"text","value":" and move "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.css "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index.css "}]}]},{"type":"text","value":"into it."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"When you do that, you will need to change the imports in your files as following:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index.js:"}]}]}]}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" ReactDOM "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react-dom'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'../styles/index.css'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" App "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./components/App'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":"  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"as"}]},{"type":"text","value":" serviceWorker "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./serviceWorker'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"2. in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js:"}]}]}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":" Component "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" logo "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./logo.svg'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'../styles/App.css'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Our directory structure should look like this now:"}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-image-card"]},"children":[{"type":"element","tagName":"img","properties":{"src":"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/1_Aqgelb3qbhJiESUbGGNUoQ.png","className":["kg-image"],"alt":"","loading":"lazy"},"children":[]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We will go ahead now and start building our webpage."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The first thing in our objectives list is showing a welcome message when the user first opens the webpage. It will show up for 3 seconds, and then changes to another message that will prompt the user to try out the trivia generator."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Without hooks, this could be done by using React’s lifecycle method "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"componentDidMount"}]},{"type":"element","tagName":"em","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"which runs right after the component first renders."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we can use the "},{"type":"element","tagName":"a","properties":{"href":"https://reactjs.org/docs/hooks-effect.html","rel":["noopener","nofollow"]},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"text","value":"effect hook"}]}]}]},{"type":"element","tagName":"em","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"instead. It will look something like this:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","comment"]},"children":[{"type":"text","value":"//perform something post render"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The function you pass to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"text","value":" will be executed after every render. This combines the lifecycles methods "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"componentDidMount"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"componentDidUpdate"}]},{"type":"text","value":" into one."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What if you want to do something just after the first time the component renders, like in "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"componentDidMount"}]},{"type":"text","value":"? You can do this by passing a second parameter to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"accepts an array as a second parameter. This parameter is used as a condition on when to perform the passed function. So, let’s say you want to change a counter only after the variable "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"counter "}]}]},{"type":"text","value":"changes, you can do it like so:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" document"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"title "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","template-string"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","template-punctuation","string"]},"children":[{"type":"text","value":"`"}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"You have clicked "}]},{"type":"element","tagName":"span","properties":{"className":["token","interpolation"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","interpolation-punctuation","punctuation"]},"children":[{"type":"text","value":"${"}]},{"type":"text","value":"counter"},{"type":"element","tagName":"span","properties":{"className":["token","interpolation-punctuation","punctuation"]},"children":[{"type":"text","value":"}"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":" times"}]},{"type":"element","tagName":"span","properties":{"className":["token","template-punctuation","string"]},"children":[{"type":"text","value":"`"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"text","value":"counter"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This way, the function passed to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"text","value":" will run after render only if the value for "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"counter"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"changes."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"If we want the function to run only after the first render, we can do that by passing an "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"empty"}]}]},{"type":"text","value":" array as the second parameter."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s come back now to what we want to do. We want to show a welcome message when the user first opens the page, then change that message after 3 seconds. We can do that by adding the following inside "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js"}]}]},{"type":"text","value":":"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"useEffect"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" Form "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./Form'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'../styles/App.css'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"App"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setTimeout"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" welcomeMessage "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" document"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"getElementById"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"welcomeMessage\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n       welcomeMessage"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"innerHTML "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"Try Out Our Trivia Generator!\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","number"]},"children":[{"type":"text","value":"3000"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"header className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App-header\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"h1 id"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"welcomeMessage\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Welcome to Numbers Trivia"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"h1"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"Form "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"header"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" App"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here’s what we’re doing:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 1:"}]}]},{"type":"text","value":" We added an import for "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 4: "}]}]},{"type":"text","value":"We changed our class component into a function component"}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 5–10: "}]}]},{"type":"text","value":"we added an effect to our function component. This effect sets a timer after 3 seconds that will change the text in the element with the id "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"welcomeMessage"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":". "}]}]},{"type":"text","value":"Because we passed an "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"empty"}]}]},{"type":"text","value":" array to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"text","value":", this effect will only run once."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 11–17: "}]}]},{"type":"text","value":"We replaced the previous code in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js "}]}]},{"type":"text","value":"to render an "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"h1 "}]}]},{"type":"text","value":"element having the id "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"welcomeMessage"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":", "}]}]},{"type":"text","value":"which is our target element."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Okay, now go to our web page and see the changes. At first, the welcome message “"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Welcome to Numbers Trivia!"}]}]},{"type":"text","value":"” will show up, then 3 seconds later it will change into “"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Try Out Our Trivia Generator!"}]}]},{"type":"text","value":"” We just used a React Hook!"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Next, let’s create our form input elements. To do that, we will create a new React component called "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":". "}]}]},{"type":"text","value":"Create in the directory "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"components"}]}]},{"type":"text","value":" the file "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form.js. "}]}]},{"type":"text","value":"For now, it will just include the following:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"props"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" Form"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This will create the new React component. We’re just importing React, then we’re creating a function called Form. As we said earlier in the tutorial, with the use of hooks we can now create components as stateful functions rather than classes. And in the last line, we’re exporting "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form"}]}]},{"type":"text","value":" in order to import it in other files."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In the form, we will have a "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"text "}]}]},{"type":"text","value":"input and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"select "}]}]},{"type":"text","value":"elements. This is based on the API we’re using. In the API, two parameters can be sent:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"number: "}]}]},{"type":"text","value":"the number you want to get the trivia for. It can be an "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"integer"}]}]},{"type":"text","value":", a date of the form "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"month/day, "}]}]},{"type":"text","value":"or the keyword "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"random "}]}]},{"type":"text","value":"which will retrieve facts about a random number."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"type: "}]}]},{"type":"text","value":"the type of information you want to get. There are a few types: "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"math, date, year, "}]}]},{"type":"text","value":"or, the default, "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"trivia."}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We will consider the text input element as optional. If the user does not enter a number or a date, we will send the keyword "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"random"}]}]},{"type":"text","value":" for the number element."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s add the following code inside the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form"}]}]},{"type":"text","value":" function in order to render our form:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"props"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"form"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"input type"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"text\""}]},{"type":"text","value":" name"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"number\""}]},{"type":"text","value":" placeholder"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"Enter a number (Optional)\""}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"select name"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"type\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n               "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"trivia\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Trivia"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n               "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"math\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Math"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n               "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"date\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Date"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n               "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"year\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Year"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"select"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n             "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"button type"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"submit\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Generate"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"button"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"form"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This will create the form with the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"text "}]}]},{"type":"text","value":"input and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"select "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"button "}]}]},{"type":"text","value":"elements."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"After that, we need to import and render the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form"}]}]},{"type":"text","value":" component in our "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App "}]}]},{"type":"text","value":"component:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"useEffect"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" Form "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'./Form'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'../styles/App.css'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"App"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useEffect"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setTimeout"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"=>"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" welcomeMessage "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" document"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"getElementById"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"welcomeMessage\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n       welcomeMessage"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"innerHTML "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"Try Out Our Trivia Generator!\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","number"]},"children":[{"type":"text","value":"3000"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"header className"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"App-header\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"h1 id"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"welcomeMessage\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Welcome to Numbers Trivia"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"h1"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"Form "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"header"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n     "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" App"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We have changed the imports to import our "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"component, and we added "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"<Form />"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"to render the form."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s also add more styles just to make our form look a little better. Add the following at the end of "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.css"}]}]},{"type":"text","value":":"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"form"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"font-size"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 15px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"form input, form select"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"padding"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 5px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"form select"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"width"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 100%"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" \n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"  \n"},{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"form div"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n   "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"margin-bottom"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 8px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"If you refresh the page now, you will find it has changed and now it’s showing our form."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we need to add some logic to our form. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"On Submit"}]}]},{"type":"text","value":", we need to get the values of our input elements, then call the API to retrieve the results."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"To handle form elements and their values, you need to use the state of the component. You make the value of the element equal to a property in the state of the component."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Before hooks, in order to get the value in the state you would have to use "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"this.state.value"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":", "}]}]},{"type":"text","value":"and then to set the state, you will need to call "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"this.setState"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, you can use the state hook. The state hook is the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"function. It accepts one argument, which is the initial value, and it returns a pair of values: the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"current state"}]}]},{"type":"text","value":" and a "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"function"}]}]},{"type":"text","value":" that updates it. Then, you will be able to access the current state using the first returned value, and update it using the second returned value which is the function."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here’s an example:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"const"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"text","value":"count"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" setCount"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","number"]},"children":[{"type":"text","value":"0"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"in this example, we call the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"hook and pass it 0, and we set the returned value equal to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"count"}]},{"type":"text","value":" and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"setCount"}]},{"type":"text","value":". This means that we have created state variable called "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"count"}]},{"type":"text","value":". Its initial value is 0, and to change its value we can use "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"setCount"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"For our "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"component, we need two state variables, one for the text"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"input which we will call "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"number"}]},{"type":"text","value":", and one for the select"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"input which we will call "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"type"}]},{"type":"text","value":". Then, on change event for these two input elements, we will change the values for "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"number"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"type"}]},{"type":"text","value":" using the function returned by "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"setState"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"."}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Open our "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":" "}]}]},{"type":"text","value":"component and change it to the following:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"import"}]},{"type":"text","value":" React"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":" useState "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"from"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'react'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"Form"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"props"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"text","value":"number"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" setNumber"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"random\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"["}]},{"type":"text","value":"type"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" setType"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"]"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"useState"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"trivia\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"onNumberChanged"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"e"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" value "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" e"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"target"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"trim"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"if"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"length"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n      "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setNumber"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"random\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","comment"]},"children":[{"type":"text","value":"//default value"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"else"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n      "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setNumber"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"onTypeChanged"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"e"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" value "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" e"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"target"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"trim"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"if"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"!"}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"length"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n      "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setType"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"trivia\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","comment"]},"children":[{"type":"text","value":"//default value"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"else"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n      "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"setType"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"value"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n  "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"return"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"form"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"input type"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"text\""}]},{"type":"text","value":" name"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"number\""}]},{"type":"text","value":" placeholder"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"Enter a number (Optional)\""}]},{"type":"text","value":" value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"number"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" onChange"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"onNumberChanged"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"select name"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"type\""}]},{"type":"text","value":" value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"type"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":" onChange"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"onTypeChanged"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n                "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"trivia\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Trivia"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n                "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"math\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Math"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n                "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"date\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Date"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n                "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"option value"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"year\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Year"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"option"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n              "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"select"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"div"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n            "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"button type"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"submit\""}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"Generate"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"button"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"<"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"/"}]},{"type":"text","value":"form"},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":">"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"export"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"default"}]},{"type":"text","value":" Form"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 1: "}]}]},{"type":"text","value":"add an import for "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"text","value":" hook."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 3–4: "}]}]},{"type":"text","value":"create two state variables "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"number"}]},{"type":"text","value":" and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"type"}]},{"type":"text","value":" using "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"text","value":" . Here we pass "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"random "}]}]},{"type":"text","value":"as the initial value for number, and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"trivia "}]}]},{"type":"text","value":"as initial value for type because they are the default values for the parameters in the API."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 5–10: "}]}]},{"type":"text","value":"implement input change handler functions for both text and select inputs, where we change the value of the state variables using the functions returned by "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"text","value":" . If the value is unset, we automatically change the values to the default value."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 13: "}]}]},{"type":"text","value":"pass the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onNumberChanged"}]},{"type":"text","value":" function to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onChange"}]},{"type":"text","value":" event for text input."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 16: "}]}]},{"type":"text","value":"pass the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onTypeChanged"}]},{"type":"text","value":" function to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onChange"}]},{"type":"text","value":" event for select input."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In addition, let’s go back to our "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"App"}]},{"type":"text","value":" component to modify it and use states. Instead of modifying our welcome message by changing the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"innerHTML"}]},{"type":"text","value":" of the element, we will use a state. Our App component should now be like this:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"text"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-text"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"import React, {useEffect, useState} from 'react'; \nimport Form from './Form'; \nimport '../styles/App.css'; \n \nfunction App() {\n  const [ welcomeMessage, setWelcomeMessage ] = useState(\n    \"Welcome to Numbers Trivia!\",\n  );\nuseEffect(() => {\n    setTimeout(() => {\n      setWelcomeMessage(\"Try Out Our Trivia Generator!\");\n    }, 3000);\n  }, []);\nreturn (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <h1>{welcomeMessage}</h1>\n      </header>\n      <Form/>\n    </div>\n  );\n}\nexport default App;"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we are using "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"useState"}]},{"type":"text","value":" to declare and initialize our welcome message. It will return "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"welcomeMessage"}]},{"type":"text","value":" , our state variable, and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"setWelcomeMessage"}]},{"type":"text","value":" , which we will use to change the value of "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"welcomeMessage"}]},{"type":"text","value":" after 3 seconds from “"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Welcome to Numbers Trivia!"}]}]},{"type":"text","value":"” to “"},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Try Out Our Trivia Generator!"}]}]},{"type":"text","value":"”"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What’s left now is to add a function to handle the form’s "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onSubmit"}]},{"type":"text","value":" event. On submit, we will send a request to the API with our parameters, then display the result."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In order to perform the request, we need to install "},{"type":"element","tagName":"a","properties":{"href":"https://github.com/axios/axios","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"axios"}]},{"type":"text","value":":"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"shell"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-shell"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"npm"}]},{"type":"text","value":" i axios"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Then, require axios at the beginning of "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form.js:"}]}]}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"const"}]},{"type":"text","value":" axios "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"require"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'axios'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, add the following function below "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onTypeChanged"}]},{"type":"text","value":" in our "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Form"}]}]},{"type":"text","value":" component:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"js"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-js"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"onSubmit"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"e"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n  e"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"preventDefault"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n  axios"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"get"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'http://numbersapi.com/'"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"+"}]},{"type":"text","value":" number "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"+"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'/'"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"+"}]},{"type":"text","value":" type"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"then"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"response"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n         "},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"let"}]},{"type":"text","value":" elm "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" document"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"getElementById"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'result'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n         elm"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"innerHTML "},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":"="}]},{"type":"text","value":" response"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"text","value":"data"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"catch"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","keyword"]},"children":[{"type":"text","value":"function"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","parameter"]},"children":[{"type":"text","value":"e"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n         console"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"."}]},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"log"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"\"error\""}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" e"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","comment"]},"children":[{"type":"text","value":"//simple error handling"}]},{"type":"text","value":"\n       "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We’re just performing a request to the API, passing the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"number"}]},{"type":"text","value":" and "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"type"}]},{"type":"text","value":" then displaying the result in an element of id "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"result"}]},{"type":"text","value":" (which we will add in a minute). In case of an error, we’re just displaying it in the console just as a simple error handling."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, let’s add this function as the handler for the form "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"onSubmit"}]},{"type":"text","value":" event in the return statement in Form.js:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"jsx"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-jsx"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-jsx"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"form"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"onSubmit"}]},{"type":"element","tagName":"span","properties":{"className":["token","script","language-javascript"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","script-punctuation","punctuation"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"onSubmit"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The only thing left is to add the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"#result"}]},{"type":"text","value":" element. We can add it in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"App.js "}]}]},{"type":"text","value":"before "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"<Form />"}]},{"type":"text","value":" :"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"jsx"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-jsx"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-jsx"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"id"}]},{"type":"element","tagName":"span","properties":{"className":["token","attr-value"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation","attr-equals"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]},{"type":"text","value":"result"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"style"}]},{"type":"element","tagName":"span","properties":{"className":["token","script","language-javascript"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","script-punctuation","punctuation"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"element","tagName":"span","properties":{"className":["token","literal-property","property"]},"children":[{"type":"text","value":"marginBottom"}]},{"type":"element","tagName":"span","properties":{"className":["token","operator"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","string"]},"children":[{"type":"text","value":"'15px'"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"</"}]},{"type":"text","value":"div"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Alright, now go to your website and discover all new trivia about numbers!"}]},{"type":"element","tagName":"hr","properties":{},"children":[]},{"type":"element","tagName":"h2","properties":{"id":"conclusion"},"children":[{"type":"text","value":"Conclusion"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"You just created a React app and used some React Hooks! Of course, there’s still more to explore and learn, so be sure to head to the "},{"type":"element","tagName":"a","properties":{"href":"https://reactjs.org/docs/hooks-intro.html","rel":["noopener","nofollow"]},"children":[{"type":"text","value":"docs"}]},{"type":"text","value":" to learn more about React Hooks."}]}],"data":{"quirksMode":false}},"tableOfContents":[{"id":"conclusion","heading":"Conclusion"}]},"featureImageSharp":{"base":"1_-Ijet6kVJqGgul6adezDLQ.png","publicURL":"/static/811e7e5724a90f775f8832f17c9353ff/1_-Ijet6kVJqGgul6adezDLQ.png","imageMeta":{"width":700,"height":350},"childImageSharp":{"fluid":{"base64":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAKCAIAAAA7N+mxAAAACXBIWXMAAAsTAAALEwEAmpwYAAABLElEQVQoz5WS3UrDQBCF8yDd7M5MdwesMf2NpSaUPkAvJCUNUqxKoNKgEStUsMU7vRJ8ZKFp2kYv1MMy7M03ezhnLTwU0fb8Tdb+CgBSbue3jb/DWpuTetWwcVwA2FCU7yyWEGxUhonAFlxvdW/uzubL5vkFgEIAIQQiMjMiGmOEEMystcaCt3LDpE07mvaXb4PVR/CwNt3A67Rns9nldBqORkmSxHGcZdlkMvF937bt3FQBG26Pr/vP74PXzyBbm17/1PPSNE2SJAzDeZrGcfy4WERRNBwOK5XKAUykbMEtr3f75N+/dMZXoBQiSimZ2XEcw1yr1aSUjUaDmaFke/M6ac1uUx8dG8fFIjAAUErlk4iklD8C21dlg1K7qqjQLnkq12aVK63+65N8AWEWZr2hm3MKAAAAAElFTkSuQmCC","aspectRatio":2,"src":"/static/811e7e5724a90f775f8832f17c9353ff/60290/1_-Ijet6kVJqGgul6adezDLQ.png","srcSet":"/static/811e7e5724a90f775f8832f17c9353ff/bcfcb/1_-Ijet6kVJqGgul6adezDLQ.png 260w,\n/static/811e7e5724a90f775f8832f17c9353ff/19d75/1_-Ijet6kVJqGgul6adezDLQ.png 520w,\n/static/811e7e5724a90f775f8832f17c9353ff/60290/1_-Ijet6kVJqGgul6adezDLQ.png 700w","srcWebp":"/static/811e7e5724a90f775f8832f17c9353ff/89afa/1_-Ijet6kVJqGgul6adezDLQ.webp","srcSetWebp":"/static/811e7e5724a90f775f8832f17c9353ff/dc8f3/1_-Ijet6kVJqGgul6adezDLQ.webp 260w,\n/static/811e7e5724a90f775f8832f17c9353ff/2db4b/1_-Ijet6kVJqGgul6adezDLQ.webp 520w,\n/static/811e7e5724a90f775f8832f17c9353ff/89afa/1_-Ijet6kVJqGgul6adezDLQ.webp 700w","sizes":"(max-width: 700px) 100vw, 700px"}}}},"prev":{"id":"Ghost__Post__6127ba1b3ed159214d382e6c","title":"CSS Variables and How To Use Them","slug":"css-variables-and-how-to-use-them","featured":false,"feature_image":"https://res-2.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/carbon--1-.png","excerpt":"A lot of people don’t know about CSS variables, and you might be one of them! It’s time to learn about CSS variables and how you can use them.","custom_excerpt":"A lot of people don’t know about CSS variables, and you might be one of them! It’s time to learn about CSS variables and how you can use them.","visibility":"public","created_at_pretty":"26 Oct 2020","published_at_pretty":"21 Apr 2019","updated_at_pretty":"26 Aug 2021","created_at":"2020-10-26T21:28:48.000+00:00","published_at":"2019-04-21T21:28:00.000+00:00","updated_at":"2021-08-26T17:54:30.000+00:00","meta_title":null,"meta_description":null,"og_description":null,"og_image":null,"og_title":null,"twitter_description":null,"twitter_image":null,"twitter_title":null,"authors":[{"slug":"shahed","url":"https://backend.shahednasser.com/author/shahed/","name":"Shahed Nasser","bio":null,"cover_image":null,"profile_image":"https://backend.shahednasser.com/content/images/2022/03/IMG_0591.jpg","location":null,"website":null,"twitter":null,"facebook":null,"meta_title":null,"meta_description":null,"coverImageSharp":null,"profileImageSharp":null}],"primary_author":{"slug":"shahed","url":"https://backend.shahednasser.com/author/shahed/","name":"Shahed Nasser","bio":null,"cover_image":null,"profile_image":"https://backend.shahednasser.com/content/images/2022/03/IMG_0591.jpg","location":null,"website":null,"twitter":null,"facebook":null,"meta_title":null,"meta_description":null,"coverImageSharp":null,"profileImageSharp":{"base":"IMG_0591.jpg","publicURL":"/static/ceb49c3c631485453e71e00d7f84b069/IMG_0591.jpg","imageMeta":{"width":1182,"height":1179},"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAMEAQL/xAAWAQEBAQAAAAAAAAAAAAAAAAADBAL/2gAMAwEAAhADEAAAAdXiFM6i0CohUWXoKn//xAAcEAACAgIDAAAAAAAAAAAAAAACAwESBBEhM0H/2gAIAQEAAQUCWySE3WEr7SzbXjAj4iKty+sOQ//EABYRAQEBAAAAAAAAAAAAAAAAAAERIP/aAAgBAwEBPwEhj//EABQRAQAAAAAAAAAAAAAAAAAAACD/2gAIAQIBAT8BH//EAB4QAAIBBAMBAAAAAAAAAAAAAAABIRESMUECECJx/9oACAEBAAY/ApVGWvOjzgtUwLlTZA0sdL4f/8QAHBAAAwACAwEAAAAAAAAAAAAAAAERITFBkbHB/9oACAEBAAE/IahkCy+N2GwZpjQiJHJCspUFY0QrSi+HqiW2rgf/2gAMAwEAAgADAAAAEPw3/wD/xAAYEQEBAAMAAAAAAAAAAAAAAAAAARExQf/aAAgBAwEBPxCtjDqP/8QAFxEBAQEBAAAAAAAAAAAAAAAAAQAxEf/aAAgBAgEBPxBFus6Tt//EAB8QAQEAAgIBBQAAAAAAAAAAAAERACExQWFRcYGR0f/aAAgBAQABPxAuaBPPzkO1wyX7F4wkwXanfZrFQgeqE9JgS14vVOvrERIJomVBKwt2jebAeP0yVa8h1n//2Q==","aspectRatio":1,"src":"/static/ceb49c3c631485453e71e00d7f84b069/31709/IMG_0591.jpg","srcSet":"/static/ceb49c3c631485453e71e00d7f84b069/f340b/IMG_0591.jpg 28w,\n/static/ceb49c3c631485453e71e00d7f84b069/22d64/IMG_0591.jpg 55w,\n/static/ceb49c3c631485453e71e00d7f84b069/31709/IMG_0591.jpg 110w,\n/static/ceb49c3c631485453e71e00d7f84b069/aa249/IMG_0591.jpg 165w,\n/static/ceb49c3c631485453e71e00d7f84b069/0dc33/IMG_0591.jpg 220w,\n/static/ceb49c3c631485453e71e00d7f84b069/d8257/IMG_0591.jpg 1182w","srcWebp":"/static/ceb49c3c631485453e71e00d7f84b069/8678c/IMG_0591.webp","srcSetWebp":"/static/ceb49c3c631485453e71e00d7f84b069/59cda/IMG_0591.webp 28w,\n/static/ceb49c3c631485453e71e00d7f84b069/7da75/IMG_0591.webp 55w,\n/static/ceb49c3c631485453e71e00d7f84b069/8678c/IMG_0591.webp 110w,\n/static/ceb49c3c631485453e71e00d7f84b069/f282e/IMG_0591.webp 165w,\n/static/ceb49c3c631485453e71e00d7f84b069/a7b21/IMG_0591.webp 220w,\n/static/ceb49c3c631485453e71e00d7f84b069/63099/IMG_0591.webp 1182w","sizes":"(max-width: 110px) 100vw, 110px"}}}},"primary_tag":{"slug":"css","url":"https://backend.shahednasser.com/tag/css/","name":"CSS","visibility":"public","feature_image":"https://backend.shahednasser.com/content/images/2022/01/photo-1610986603166-f78428624e76-2.jpeg","description":"Learn more about CSS through tutorials, articles, and tips.","meta_title":null,"meta_description":null,"featureImageSharp":{"base":"photo-1610986603166-f78428624e76-2.jpeg","publicURL":"/static/2e4062ead6b64acea03c5c5ba3437c96/photo-1610986603166-f78428624e76-2.jpeg","imageMeta":{"width":2000,"height":1352},"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAOABQDASIAAhEBAxEB/8QAGAAAAgMAAAAAAAAAAAAAAAAAAAIBAwX/xAAVAQEBAAAAAAAAAAAAAAAAAAAAAf/aAAwDAQACEAMQAAABymIKxiv/xAAaEAACAgMAAAAAAAAAAAAAAAAAEQECEBIh/9oACAEBAAEFAqolalUcx//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQMBAT8BP//EABURAQEAAAAAAAAAAAAAAAAAAAAR/9oACAECAQE/AUf/xAAZEAACAwEAAAAAAAAAAAAAAAAQIQABEYH/2gAIAQEABj8CcVd0M//EABsQAAIDAAMAAAAAAAAAAAAAAAABESExEFGB/9oACAEBAAE/IdKGJM+nDWSDSdkH/9oADAMBAAIAAwAAABCL7//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQMBAT8QP//EABURAQEAAAAAAAAAAAAAAAAAAAEQ/9oACAECAQE/EAY//8QAGhABAQADAQEAAAAAAAAAAAAAAREAITEQYf/aAAgBAQABPxAsEuSsxwBHaV8nMjhCkPIbwwjTs8f/2Q==","aspectRatio":1.4772727272727273,"src":"/static/2e4062ead6b64acea03c5c5ba3437c96/d5c54/photo-1610986603166-f78428624e76-2.jpg","srcSet":"/static/2e4062ead6b64acea03c5c5ba3437c96/65d8c/photo-1610986603166-f78428624e76-2.jpg 260w,\n/static/2e4062ead6b64acea03c5c5ba3437c96/c5f21/photo-1610986603166-f78428624e76-2.jpg 520w,\n/static/2e4062ead6b64acea03c5c5ba3437c96/d5c54/photo-1610986603166-f78428624e76-2.jpg 1040w,\n/static/2e4062ead6b64acea03c5c5ba3437c96/81a53/photo-1610986603166-f78428624e76-2.jpg 1560w,\n/static/2e4062ead6b64acea03c5c5ba3437c96/4e5f3/photo-1610986603166-f78428624e76-2.jpg 2000w","srcWebp":"/static/2e4062ead6b64acea03c5c5ba3437c96/e4875/photo-1610986603166-f78428624e76-2.webp","srcSetWebp":"/static/2e4062ead6b64acea03c5c5ba3437c96/dc8f3/photo-1610986603166-f78428624e76-2.webp 260w,\n/static/2e4062ead6b64acea03c5c5ba3437c96/2db4b/photo-1610986603166-f78428624e76-2.webp 520w,\n/static/2e4062ead6b64acea03c5c5ba3437c96/e4875/photo-1610986603166-f78428624e76-2.webp 1040w,\n/static/2e4062ead6b64acea03c5c5ba3437c96/f5845/photo-1610986603166-f78428624e76-2.webp 1560w,\n/static/2e4062ead6b64acea03c5c5ba3437c96/49d6b/photo-1610986603166-f78428624e76-2.webp 2000w","sizes":"(max-width: 1040px) 100vw, 1040px"}}}},"tags":[{"slug":"css","url":"https://backend.shahednasser.com/tag/css/","name":"CSS","visibility":"public","feature_image":"https://backend.shahednasser.com/content/images/2022/01/photo-1610986603166-f78428624e76-2.jpeg","description":"Learn more about CSS through tutorials, articles, and tips.","meta_title":null,"meta_description":null,"featureImageSharp":null},{"slug":"beginner","url":"https://backend.shahednasser.com/tag/beginner/","name":"Beginners","visibility":"public","feature_image":"https://backend.shahednasser.com/content/images/2022/01/photo-1521185496955-15097b20c5fe-2.jpeg","description":"Tutorials, articles, and tips to help beginners accelerate their journey in programming.","meta_title":"Beginners","meta_description":"Tutorials, articles, and tips to help beginners accelerate their journey in programming.","featureImageSharp":null},{"slug":"tips","url":"https://backend.shahednasser.com/tag/tips/","name":"Tips","visibility":"public","feature_image":null,"description":"Learn more about programming and development through these articles that have essential tips!","meta_title":"Tips on Technology and Programming","meta_description":null,"featureImageSharp":null}],"plaintext":"A lot of people don’t know about CSS variables, and you might be one of them!\nIt’s time to learn about CSS variables and how you can use them.\n\nCSS variables are declared for a specific element as a custom property. Then,\nyou can use that custom property anywhere you use that element.\n\n\n--------------------------------------------------------------------------------\n\nDeclaration and Usage\nHere’s how you declare a custom property:\n\nelement { \n\t--background-color: #f00;\n}\n\nHere, element can be a selector of any element, for example, div, p, .test, etc…\n\nWhat we did is that we declared a custom property for this element called \n--background-color . All CSS custom properties must start with -- .\n\nNow, we can use this custom property inside element using the var function.\n\nelement {  \n\tbackground-color: var(--background-color);\n}\n\nHere, we assigned the background-color property of element to the variable we\ndeclared earlier.\n\nThis is nice and all, but usually we have repetition inside different elements,\nnot just one. declaring a custom variable inside one element type is not very\nconvenient.\n\nIn order to use a custom property inside more than one element type, we can\ndeclare the custom property inside the :root pseudo-class.\n\n:root {  \n\t--primary-color: #333;\n}\n\nNow, we can use the variable --primary-color inside any element in our document:\n\ndiv {  \n\tcolor: var(--primary-color);\n}\np {  \n\tbackground-color: var(--primary-color);\n}\n.fancy {  \n\tborder-color: var(--primary-color);\n}\n\nBy declaring our custom property inside :root , we are now able to use it inside \ndiv to set the text color, p to set the background color, and any element having\nclass fancy to set the border color. This way, not only did we minimize\nrepetition, but we also made it easier to edit and change our website’s primary\ncolor at any given point.\n\n\n--------------------------------------------------------------------------------\n\nInheritance\nElements can also inherit custom properties. For example, let’s say we have the\nfollowing HTML:\n\n<div class=\"parent\">\n\t<div class=\"first-child\"></div>  \n    <div class=\"second-child\"><div>\n</div>\n\nThen, we declare a variable called --text-size on .parent :\n\n.parent {  \n\t--text-size: 15px;\n}\n\nNow, we can use --text-size not only inside .parent , but also inside its\nchildren as well:\n\n.first-child {\n    font-size: var(--text-size);\n}\n\nWe can also override custom properties. We can do that by redeclaring the custom\nproperty inside the child element:\n\n.second-child {  \n\t--text-size: 30px;\n}\n\nNow, if you use --text-size inside .second-child , it’ll be evaluated to 30px,\nbut if you use it inside .first-child or .parent, it will still be 15px.\n\n\n--------------------------------------------------------------------------------\n\nFallback Values\nYou can also define a fallback value for a variable by passing a second\nparameter to var . For example:\n\n.second-child {  \n\tfont-size: var(--text-size, 30px);\n}\n\nFallback values are used when the variable is not defined yet. They are not used\nas a fallback to browser incompatibility.\n\n\n--------------------------------------------------------------------------------\n\nConclusion\nAnd that’s how you can use CSS variables! Keep in mind that some browsers like\nInternet Explorer don’t support them, so if you need to support all browsers you\nneed to take that into consideration.","html":"<p>A lot of people don’t know about CSS variables, and you might be one of them! It’s time to learn about CSS variables and how you can use them.</p><p>CSS variables are declared for a specific element as a custom property. Then, you can use that custom property anywhere you use that element.</p><hr><h1 id=\"declaration-and-usage\">Declaration and Usage</h1><p>Here’s how you declare a custom property:</p><pre><code class=\"language-css\">element { \n\t--background-color: #f00;\n}</code></pre><p>Here, <code>element</code> can be a selector of any element, for example, div, p, .test, etc…</p><p>What we did is that we declared a custom property for this element called <code>--background-color</code> . All CSS custom properties must start with <code>--</code> .</p><p>Now, we can use this custom property inside <code>element</code> using the <code>var</code> function.</p><pre><code class=\"language-css\">element {  \n\tbackground-color: var(--background-color);\n}</code></pre><p>Here, we assigned the background-color property of <code>element</code> to the variable we declared earlier.</p><p>This is nice and all, but usually we have repetition inside different elements, not just one. declaring a custom variable inside one element type is not very convenient.</p><p>In order to use a custom property inside more than one element type, we can declare the custom property inside the <code>:root</code> pseudo-class.</p><pre><code class=\"language-css\">:root {  \n\t--primary-color: #333;\n}</code></pre><p>Now, we can use the variable <code>--primary-color</code> inside any element in our document:</p><pre><code class=\"language-css\">div {  \n\tcolor: var(--primary-color);\n}\np {  \n\tbackground-color: var(--primary-color);\n}\n.fancy {  \n\tborder-color: var(--primary-color);\n}</code></pre><p>By declaring our custom property inside <code>:root</code> , we are now able to use it inside <code>div</code> to set the text color, <code>p</code> to set the background color, and any element having class <code>fancy</code> to set the border color. This way, not only did we minimize repetition, but we also made it easier to edit and change our website’s primary color at any given point.</p><hr><h1 id=\"inheritance\">Inheritance</h1><p>Elements can also inherit custom properties. For example, let’s say we have the following HTML:</p><pre><code class=\"language-html\">&lt;div class=\"parent\"&gt;\n\t&lt;div class=\"first-child\"&gt;&lt;/div&gt;  \n    &lt;div class=\"second-child\"&gt;&lt;div&gt;\n&lt;/div&gt;</code></pre><p>Then, we declare a variable called <code>--text-size</code> on <code>.parent</code> :</p><pre><code class=\"language-css\">.parent {  \n\t--text-size: 15px;\n}</code></pre><p>Now, we can use <code>--text-size</code> not only inside <code>.parent</code> , but also inside its children as well:</p><pre><code class=\"language-css\">.first-child {\n    font-size: var(--text-size);\n}</code></pre><p>We can also override custom properties. We can do that by redeclaring the custom property inside the child element:</p><pre><code class=\"language-css\">.second-child {  \n\t--text-size: 30px;\n}</code></pre><p>Now, if you use <code>--text-size</code> inside <code>.second-child</code> , it’ll be evaluated to 30px, but if you use it inside <code>.first-child</code> or <code>.parent</code>, it will still be 15px.</p><hr><h1 id=\"fallback-values\">Fallback Values</h1><p>You can also define a fallback value for a variable by passing a second parameter to <code>var</code> . For example:</p><pre><code class=\"language-css\">.second-child {  \n\tfont-size: var(--text-size, 30px);\n}</code></pre><p>Fallback values are used when the variable is not defined yet. They are <strong><strong><em><em>not</em></em></strong></strong> used as a fallback to browser incompatibility.</p><hr><h1 id=\"conclusion\">Conclusion</h1><p>And that’s how you can use CSS variables! Keep in mind that some browsers like Internet Explorer don’t support them, so if you need to support all browsers you need to take that into consideration.</p>","url":"https://backend.shahednasser.com/css-variables-and-how-to-use-them/","canonical_url":null,"uuid":"294be2c5-8cd6-41a1-94b5-28838e34c151","codeinjection_foot":null,"codeinjection_head":null,"codeinjection_styles":null,"comment_id":"5f973f90b366d4001e86cc54","reading_time":2,"send_email_when_published":null,"email_subject":null,"childHtmlRehype":{"html":"<p>A lot of people don’t know about CSS variables, and you might be one of them! It’s time to learn about CSS variables and how you can use them.</p><p>CSS variables are declared for a specific element as a custom property. Then, you can use that custom property anywhere you use that element.</p><hr><h1 id=\"declaration-and-usage\">Declaration and Usage</h1><p>Here’s how you declare a custom property:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">element</span> <span class=\"token punctuation\">{</span> \n\t<span class=\"token property\">--background-color</span><span class=\"token punctuation\">:</span> #f00<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>Here, <code class=\"language-text\">element</code> can be a selector of any element, for example, div, p, .test, etc…</p><p>What we did is that we declared a custom property for this element called <code class=\"language-text\">--background-color</code> . All CSS custom properties must start with <code class=\"language-text\">--</code> .</p><p>Now, we can use this custom property inside <code class=\"language-text\">element</code> using the <code class=\"language-text\">var</code> function.</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">element</span> <span class=\"token punctuation\">{</span>  \n\t<span class=\"token property\">background-color</span><span class=\"token punctuation\">:</span> <span class=\"token function\">var</span><span class=\"token punctuation\">(</span>--background-color<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>Here, we assigned the background-color property of <code class=\"language-text\">element</code> to the variable we declared earlier.</p><p>This is nice and all, but usually we have repetition inside different elements, not just one. declaring a custom variable inside one element type is not very convenient.</p><p>In order to use a custom property inside more than one element type, we can declare the custom property inside the <code class=\"language-text\">:root</code> pseudo-class.</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">:root</span> <span class=\"token punctuation\">{</span>  \n\t<span class=\"token property\">--primary-color</span><span class=\"token punctuation\">:</span> #333<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>Now, we can use the variable <code class=\"language-text\">--primary-color</code> inside any element in our document:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">div</span> <span class=\"token punctuation\">{</span>  \n\t<span class=\"token property\">color</span><span class=\"token punctuation\">:</span> <span class=\"token function\">var</span><span class=\"token punctuation\">(</span>--primary-color<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>\n<span class=\"token selector\">p</span> <span class=\"token punctuation\">{</span>  \n\t<span class=\"token property\">background-color</span><span class=\"token punctuation\">:</span> <span class=\"token function\">var</span><span class=\"token punctuation\">(</span>--primary-color<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>\n<span class=\"token selector\">.fancy</span> <span class=\"token punctuation\">{</span>  \n\t<span class=\"token property\">border-color</span><span class=\"token punctuation\">:</span> <span class=\"token function\">var</span><span class=\"token punctuation\">(</span>--primary-color<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>By declaring our custom property inside <code class=\"language-text\">:root</code> , we are now able to use it inside <code class=\"language-text\">div</code> to set the text color, <code class=\"language-text\">p</code> to set the background color, and any element having class <code class=\"language-text\">fancy</code> to set the border color. This way, not only did we minimize repetition, but we also made it easier to edit and change our website’s primary color at any given point.</p><hr><h1 id=\"inheritance\">Inheritance</h1><p>Elements can also inherit custom properties. For example, let’s say we have the following HTML:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"html\"><pre class=\"language-html\"><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;</span>div</span> <span class=\"token attr-name\">class</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>parent<span class=\"token punctuation\">\"</span></span><span class=\"token punctuation\">></span></span>\n\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;</span>div</span> <span class=\"token attr-name\">class</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>first-child<span class=\"token punctuation\">\"</span></span><span class=\"token punctuation\">></span></span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;/</span>div</span><span class=\"token punctuation\">></span></span>  \n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;</span>div</span> <span class=\"token attr-name\">class</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>second-child<span class=\"token punctuation\">\"</span></span><span class=\"token punctuation\">></span></span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;</span>div</span><span class=\"token punctuation\">></span></span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&#x3C;/</span>div</span><span class=\"token punctuation\">></span></span></code></pre></div><p>Then, we declare a variable called <code class=\"language-text\">--text-size</code> on <code class=\"language-text\">.parent</code> :</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">.parent</span> <span class=\"token punctuation\">{</span>  \n\t<span class=\"token property\">--text-size</span><span class=\"token punctuation\">:</span> 15px<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>Now, we can use <code class=\"language-text\">--text-size</code> not only inside <code class=\"language-text\">.parent</code> , but also inside its children as well:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">.first-child</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token property\">font-size</span><span class=\"token punctuation\">:</span> <span class=\"token function\">var</span><span class=\"token punctuation\">(</span>--text-size<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>We can also override custom properties. We can do that by redeclaring the custom property inside the child element:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">.second-child</span> <span class=\"token punctuation\">{</span>  \n\t<span class=\"token property\">--text-size</span><span class=\"token punctuation\">:</span> 30px<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>Now, if you use <code class=\"language-text\">--text-size</code> inside <code class=\"language-text\">.second-child</code> , it’ll be evaluated to 30px, but if you use it inside <code class=\"language-text\">.first-child</code> or <code class=\"language-text\">.parent</code>, it will still be 15px.</p><hr><h1 id=\"fallback-values\">Fallback Values</h1><p>You can also define a fallback value for a variable by passing a second parameter to <code class=\"language-text\">var</code> . For example:</p><div class=\"kg-card kg-code-card gatsby-highlight\" data-language=\"css\"><pre class=\"language-css\"><code class=\"language-css\"><span class=\"token selector\">.second-child</span> <span class=\"token punctuation\">{</span>  \n\t<span class=\"token property\">font-size</span><span class=\"token punctuation\">:</span> <span class=\"token function\">var</span><span class=\"token punctuation\">(</span>--text-size<span class=\"token punctuation\">,</span> 30px<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div><p>Fallback values are used when the variable is not defined yet. They are <strong><strong><em><em>not</em></em></strong></strong> used as a fallback to browser incompatibility.</p><hr><h1 id=\"conclusion\">Conclusion</h1><p>And that’s how you can use CSS variables! Keep in mind that some browsers like Internet Explorer don’t support them, so if you need to support all browsers you need to take that into consideration.</p>","htmlAst":{"type":"root","children":[{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"A lot of people don’t know about CSS variables, and you might be one of them! It’s time to learn about CSS variables and how you can use them."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"CSS variables are declared for a specific element as a custom property. Then, you can use that custom property anywhere you use that element."}]},{"type":"element","tagName":"hr","properties":{},"children":[]},{"type":"element","tagName":"h1","properties":{"id":"declaration-and-usage"},"children":[{"type":"text","value":"Declaration and Usage"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here’s how you declare a custom property:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"element"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":" \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"--background-color"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" #f00"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here, "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"element"}]},{"type":"text","value":" can be a selector of any element, for example, div, p, .test, etc…"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What we did is that we declared a custom property for this element called "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"--background-color"}]},{"type":"text","value":" . All CSS custom properties must start with "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"--"}]},{"type":"text","value":" ."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we can use this custom property inside "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"element"}]},{"type":"text","value":" using the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"var"}]},{"type":"text","value":" function."}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"element"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"  \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"background-color"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"var"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"--background-color"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here, we assigned the background-color property of "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"element"}]},{"type":"text","value":" to the variable we declared earlier."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This is nice and all, but usually we have repetition inside different elements, not just one. declaring a custom variable inside one element type is not very convenient."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In order to use a custom property inside more than one element type, we can declare the custom property inside the "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":":root"}]},{"type":"text","value":" pseudo-class."}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":":root"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"  \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"--primary-color"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" #333"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we can use the variable "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"--primary-color"}]},{"type":"text","value":" inside any element in our document:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"div"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"  \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"color"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"var"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"--primary-color"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":"p"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"  \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"background-color"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"var"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"--primary-color"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":".fancy"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"  \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"border-color"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"var"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"--primary-color"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"By declaring our custom property inside "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":":root"}]},{"type":"text","value":" , we are now able to use it inside "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"div"}]},{"type":"text","value":" to set the text color, "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"p"}]},{"type":"text","value":" to set the background color, and any element having class "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"fancy"}]},{"type":"text","value":" to set the border color. This way, not only did we minimize repetition, but we also made it easier to edit and change our website’s primary color at any given point."}]},{"type":"element","tagName":"hr","properties":{},"children":[]},{"type":"element","tagName":"h1","properties":{"id":"inheritance"},"children":[{"type":"text","value":"Inheritance"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Elements can also inherit custom properties. For example, let’s say we have the following HTML:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"html"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-html"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-html"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"class"}]},{"type":"element","tagName":"span","properties":{"className":["token","attr-value"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation","attr-equals"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]},{"type":"text","value":"parent"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]},{"type":"text","value":"\n\t"},{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"class"}]},{"type":"element","tagName":"span","properties":{"className":["token","attr-value"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation","attr-equals"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]},{"type":"text","value":"first-child"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"</"}]},{"type":"text","value":"div"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]},{"type":"text","value":"  \n    "},{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","attr-name"]},"children":[{"type":"text","value":"class"}]},{"type":"element","tagName":"span","properties":{"className":["token","attr-value"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation","attr-equals"]},"children":[{"type":"text","value":"="}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]},{"type":"text","value":"second-child"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"\""}]}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]},{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"<"}]},{"type":"text","value":"div"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","tag"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"</"}]},{"type":"text","value":"div"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":">"}]}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Then, we declare a variable called "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"--text-size"}]},{"type":"text","value":" on "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":".parent"}]},{"type":"text","value":" :"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":".parent"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"  \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"--text-size"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 15px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we can use "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"--text-size"}]},{"type":"text","value":" not only inside "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":".parent"}]},{"type":"text","value":" , but also inside its children as well:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":".first-child"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"\n    "},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"font-size"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"var"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"--text-size"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We can also override custom properties. We can do that by redeclaring the custom property inside the child element:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":".second-child"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"  \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"--text-size"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" 30px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, if you use "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"--text-size"}]},{"type":"text","value":" inside "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":".second-child"}]},{"type":"text","value":" , it’ll be evaluated to 30px, but if you use it inside "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":".first-child"}]},{"type":"text","value":" or "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":".parent"}]},{"type":"text","value":", it will still be 15px."}]},{"type":"element","tagName":"hr","properties":{},"children":[]},{"type":"element","tagName":"h1","properties":{"id":"fallback-values"},"children":[{"type":"text","value":"Fallback Values"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"You can also define a fallback value for a variable by passing a second parameter to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"var"}]},{"type":"text","value":" . For example:"}]},{"type":"element","tagName":"div","properties":{"className":["kg-card","kg-code-card","gatsby-highlight"],"dataLanguage":"css"},"children":[{"type":"element","tagName":"pre","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"code","properties":{"className":["language-css"]},"children":[{"type":"element","tagName":"span","properties":{"className":["token","selector"]},"children":[{"type":"text","value":".second-child"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"{"}]},{"type":"text","value":"  \n\t"},{"type":"element","tagName":"span","properties":{"className":["token","property"]},"children":[{"type":"text","value":"font-size"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":":"}]},{"type":"text","value":" "},{"type":"element","tagName":"span","properties":{"className":["token","function"]},"children":[{"type":"text","value":"var"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"("}]},{"type":"text","value":"--text-size"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":","}]},{"type":"text","value":" 30px"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":")"}]},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":";"}]},{"type":"text","value":"\n"},{"type":"element","tagName":"span","properties":{"className":["token","punctuation"]},"children":[{"type":"text","value":"}"}]}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Fallback values are used when the variable is not defined yet. They are "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"text","value":"not"}]}]}]}]},{"type":"text","value":" used as a fallback to browser incompatibility."}]},{"type":"element","tagName":"hr","properties":{},"children":[]},{"type":"element","tagName":"h1","properties":{"id":"conclusion"},"children":[{"type":"text","value":"Conclusion"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"And that’s how you can use CSS variables! Keep in mind that some browsers like Internet Explorer don’t support them, so if you need to support all browsers you need to take that into consideration."}]}],"data":{"quirksMode":false}},"tableOfContents":[{"id":"declaration-and-usage","heading":"Declaration and Usage"},{"id":"inheritance","heading":"Inheritance"},{"id":"fallback-values","heading":"Fallback Values"},{"id":"conclusion","heading":"Conclusion"}]},"featureImageSharp":{"base":"carbon--1-.png","publicURL":"/static/ffa580b4a342c60287433e8f82cb8e58/carbon--1-.png","imageMeta":{"width":1080,"height":836},"childImageSharp":{"fluid":{"base64":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAPCAYAAADkmO9VAAAACXBIWXMAAAsTAAALEwEAmpwYAAAB8klEQVQ4y6WUy27aQBSGeZaCTTC2xzeMjT2AjblfWilqVVXpE7RSVlGbRdVdV5SEKH06IqKEVcI7+K9m7HBpXRKpi8//eGbOr3PsM5PrX9xhcHmP3vUDuldrDK/WGP1aY/hC+N7rR+7BvHKDyxW6P5cIP3xH5+QzzJNT6JNT6G9ehjb5BOv9N/RnSzCv3HC+Qnu6gOd10KQSRErwSlJRUFQUZBV5eau7Y6YFhSAvSThyIvSmCwzmqyTD/vQGRTpGXnch+20ofoii5UE0XIhmjVNMEffwIGgVSPUJetObJEP2YC8SHUGqOChaNcheEyTsQqm3EmiIiu3BdCgEw4GoVyEyNVwIxOSxmYalipts2gQ4yVivcn2aF9K1g4al+giyYYNYHkq2v2+6MXA2xsn6MxlKZhXliget1QEJIqgNVnIIhQb8M6g0hOwHIK0uZBpCaUTQ2Fp9vP9TNoZ2DQXdRUGrbsvdyS6LAxmOUTRtELcGxfH/Ki+L7JLniWG58ZpnSGoURtSB7AVQaIu3kNJoQ212UPZDrqoXpC2V1TbccIEjN0LJ0JGXNeQVAkFlaIkSLR1vOdDY93F/toztjz9i4/gstt6dx+bbrylfdvRP2Px5bB6f8VjmwbxyT5cDO+CjnQP/HP+8HPoXdw+c2e3/kfr8BonVY0AbLAheAAAAAElFTkSuQmCC","aspectRatio":1.2962962962962963,"src":"/static/ffa580b4a342c60287433e8f82cb8e58/60290/carbon--1-.png","srcSet":"/static/ffa580b4a342c60287433e8f82cb8e58/847ef/carbon--1-.png 175w,\n/static/ffa580b4a342c60287433e8f82cb8e58/91cba/carbon--1-.png 350w,\n/static/ffa580b4a342c60287433e8f82cb8e58/60290/carbon--1-.png 700w,\n/static/ffa580b4a342c60287433e8f82cb8e58/f5f50/carbon--1-.png 1050w,\n/static/ffa580b4a342c60287433e8f82cb8e58/14010/carbon--1-.png 1080w","srcWebp":"/static/ffa580b4a342c60287433e8f82cb8e58/89afa/carbon--1-.webp","srcSetWebp":"/static/ffa580b4a342c60287433e8f82cb8e58/9fca7/carbon--1-.webp 175w,\n/static/ffa580b4a342c60287433e8f82cb8e58/37a4e/carbon--1-.webp 350w,\n/static/ffa580b4a342c60287433e8f82cb8e58/89afa/carbon--1-.webp 700w,\n/static/ffa580b4a342c60287433e8f82cb8e58/78e7a/carbon--1-.webp 1050w,\n/static/ffa580b4a342c60287433e8f82cb8e58/788b4/carbon--1-.webp 1080w","sizes":"(max-width: 700px) 100vw, 700px"}}}},"next":{"id":"Ghost__Post__6127ba1b3ed159214d382e71","title":"Chrome Extension Tutorial — Replace Images in Any Website with Pikachu","slug":"chrome-extension-tutorial-replace-images-in-any-website-with-pikachu","featured":false,"feature_image":"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension.gif","excerpt":"What’s a better way to learn how to make a Chrome extension than making the web cuter with Pikachu images?","custom_excerpt":"What’s a better way to learn how to make a Chrome extension than making the web cuter with Pikachu images?","visibility":"public","created_at_pretty":"6 Nov 2020","published_at_pretty":"11 Apr 2019","updated_at_pretty":"26 Aug 2021","created_at":"2020-11-06T18:32:10.000+00:00","published_at":"2019-04-11T18:30:00.000+00:00","updated_at":"2021-08-26T17:55:09.000+00:00","meta_title":null,"meta_description":null,"og_description":null,"og_image":null,"og_title":null,"twitter_description":null,"twitter_image":null,"twitter_title":null,"authors":[{"slug":"shahed","url":"https://backend.shahednasser.com/author/shahed/","name":"Shahed Nasser","bio":null,"cover_image":null,"profile_image":"https://backend.shahednasser.com/content/images/2022/03/IMG_0591.jpg","location":null,"website":null,"twitter":null,"facebook":null,"meta_title":null,"meta_description":null,"coverImageSharp":null,"profileImageSharp":null}],"primary_author":{"slug":"shahed","url":"https://backend.shahednasser.com/author/shahed/","name":"Shahed Nasser","bio":null,"cover_image":null,"profile_image":"https://backend.shahednasser.com/content/images/2022/03/IMG_0591.jpg","location":null,"website":null,"twitter":null,"facebook":null,"meta_title":null,"meta_description":null,"coverImageSharp":null,"profileImageSharp":{"base":"IMG_0591.jpg","publicURL":"/static/ceb49c3c631485453e71e00d7f84b069/IMG_0591.jpg","imageMeta":{"width":1182,"height":1179},"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAMEAQL/xAAWAQEBAQAAAAAAAAAAAAAAAAADBAL/2gAMAwEAAhADEAAAAdXiFM6i0CohUWXoKn//xAAcEAACAgIDAAAAAAAAAAAAAAACAwESBBEhM0H/2gAIAQEAAQUCWySE3WEr7SzbXjAj4iKty+sOQ//EABYRAQEBAAAAAAAAAAAAAAAAAAERIP/aAAgBAwEBPwEhj//EABQRAQAAAAAAAAAAAAAAAAAAACD/2gAIAQIBAT8BH//EAB4QAAIBBAMBAAAAAAAAAAAAAAABIRESMUECECJx/9oACAEBAAY/ApVGWvOjzgtUwLlTZA0sdL4f/8QAHBAAAwACAwEAAAAAAAAAAAAAAAERITFBkbHB/9oACAEBAAE/IahkCy+N2GwZpjQiJHJCspUFY0QrSi+HqiW2rgf/2gAMAwEAAgADAAAAEPw3/wD/xAAYEQEBAAMAAAAAAAAAAAAAAAAAARExQf/aAAgBAwEBPxCtjDqP/8QAFxEBAQEBAAAAAAAAAAAAAAAAAQAxEf/aAAgBAgEBPxBFus6Tt//EAB8QAQEAAgIBBQAAAAAAAAAAAAERACExQWFRcYGR0f/aAAgBAQABPxAuaBPPzkO1wyX7F4wkwXanfZrFQgeqE9JgS14vVOvrERIJomVBKwt2jebAeP0yVa8h1n//2Q==","aspectRatio":1,"src":"/static/ceb49c3c631485453e71e00d7f84b069/31709/IMG_0591.jpg","srcSet":"/static/ceb49c3c631485453e71e00d7f84b069/f340b/IMG_0591.jpg 28w,\n/static/ceb49c3c631485453e71e00d7f84b069/22d64/IMG_0591.jpg 55w,\n/static/ceb49c3c631485453e71e00d7f84b069/31709/IMG_0591.jpg 110w,\n/static/ceb49c3c631485453e71e00d7f84b069/aa249/IMG_0591.jpg 165w,\n/static/ceb49c3c631485453e71e00d7f84b069/0dc33/IMG_0591.jpg 220w,\n/static/ceb49c3c631485453e71e00d7f84b069/d8257/IMG_0591.jpg 1182w","srcWebp":"/static/ceb49c3c631485453e71e00d7f84b069/8678c/IMG_0591.webp","srcSetWebp":"/static/ceb49c3c631485453e71e00d7f84b069/59cda/IMG_0591.webp 28w,\n/static/ceb49c3c631485453e71e00d7f84b069/7da75/IMG_0591.webp 55w,\n/static/ceb49c3c631485453e71e00d7f84b069/8678c/IMG_0591.webp 110w,\n/static/ceb49c3c631485453e71e00d7f84b069/f282e/IMG_0591.webp 165w,\n/static/ceb49c3c631485453e71e00d7f84b069/a7b21/IMG_0591.webp 220w,\n/static/ceb49c3c631485453e71e00d7f84b069/63099/IMG_0591.webp 1182w","sizes":"(max-width: 110px) 100vw, 110px"}}}},"primary_tag":{"slug":"browser-extensions","url":"https://backend.shahednasser.com/tag/browser-extensions/","name":"Browser Extensions","visibility":"public","feature_image":"https://backend.shahednasser.com/content/images/2022/01/photo-1616499370260-485b3e5ed653-2.jpeg","description":"Learn more about Browser Extensions through tutorials, articles, and tips.","meta_title":null,"meta_description":null,"featureImageSharp":{"base":"photo-1616499370260-485b3e5ed653-2.jpeg","publicURL":"/static/17d3062927434b0d9d22f3e45ece68b8/photo-1616499370260-485b3e5ed653-2.jpeg","imageMeta":{"width":2000,"height":1334},"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAGAAAAgMAAAAAAAAAAAAAAAAAAAMCBAX/xAAVAQEBAAAAAAAAAAAAAAAAAAAAAv/aAAwDAQACEAMQAAABQ+hsRUBAf//EABoQAQADAAMAAAAAAAAAAAAAAAIAAQMEEyL/2gAIAQEAAQUCKpA3nefSo/JALzvlaXP/xAAVEQEBAAAAAAAAAAAAAAAAAAAQEf/aAAgBAwEBPwGH/8QAFREBAQAAAAAAAAAAAAAAAAAAERD/2gAIAQIBAT8BSf/EAB4QAAEDBAMAAAAAAAAAAAAAAAEAAiEDEBEiMVFh/9oACAEBAAY/Ai1x9CG2/VmEcoVCJwogL//EABoQAQEBAQADAAAAAAAAAAAAAAERACFBcYH/2gAIAQEAAT8h6pD2YW6ifbqrwMDk3W6VFUxyFZ4ib//aAAwDAQACAAMAAAAQLB//xAAXEQEAAwAAAAAAAAAAAAAAAAAAAREh/9oACAEDAQE/EJs1/8QAFREBAQAAAAAAAAAAAAAAAAAAABH/2gAIAQIBAT8QFf/EABwQAQEAAwEAAwAAAAAAAAAAAAERACExQVFhgf/aAAgBAQABPxCsM1ex6ZRBIol9InPbigkXRbrDW2E9042KoTWHL8fWeOKEM/Xuf//Z","aspectRatio":1.5028901734104045,"src":"/static/17d3062927434b0d9d22f3e45ece68b8/d5c54/photo-1616499370260-485b3e5ed653-2.jpg","srcSet":"/static/17d3062927434b0d9d22f3e45ece68b8/65d8c/photo-1616499370260-485b3e5ed653-2.jpg 260w,\n/static/17d3062927434b0d9d22f3e45ece68b8/c5f21/photo-1616499370260-485b3e5ed653-2.jpg 520w,\n/static/17d3062927434b0d9d22f3e45ece68b8/d5c54/photo-1616499370260-485b3e5ed653-2.jpg 1040w,\n/static/17d3062927434b0d9d22f3e45ece68b8/81a53/photo-1616499370260-485b3e5ed653-2.jpg 1560w,\n/static/17d3062927434b0d9d22f3e45ece68b8/4e5f3/photo-1616499370260-485b3e5ed653-2.jpg 2000w","srcWebp":"/static/17d3062927434b0d9d22f3e45ece68b8/e4875/photo-1616499370260-485b3e5ed653-2.webp","srcSetWebp":"/static/17d3062927434b0d9d22f3e45ece68b8/dc8f3/photo-1616499370260-485b3e5ed653-2.webp 260w,\n/static/17d3062927434b0d9d22f3e45ece68b8/2db4b/photo-1616499370260-485b3e5ed653-2.webp 520w,\n/static/17d3062927434b0d9d22f3e45ece68b8/e4875/photo-1616499370260-485b3e5ed653-2.webp 1040w,\n/static/17d3062927434b0d9d22f3e45ece68b8/f5845/photo-1616499370260-485b3e5ed653-2.webp 1560w,\n/static/17d3062927434b0d9d22f3e45ece68b8/49d6b/photo-1616499370260-485b3e5ed653-2.webp 2000w","sizes":"(max-width: 1040px) 100vw, 1040px"}}}},"tags":[{"slug":"browser-extensions","url":"https://backend.shahednasser.com/tag/browser-extensions/","name":"Browser Extensions","visibility":"public","feature_image":"https://backend.shahednasser.com/content/images/2022/01/photo-1616499370260-485b3e5ed653-2.jpeg","description":"Learn more about Browser Extensions through tutorials, articles, and tips.","meta_title":null,"meta_description":null,"featureImageSharp":null},{"slug":"beginner","url":"https://backend.shahednasser.com/tag/beginner/","name":"Beginners","visibility":"public","feature_image":"https://backend.shahednasser.com/content/images/2022/01/photo-1521185496955-15097b20c5fe-2.jpeg","description":"Tutorials, articles, and tips to help beginners accelerate their journey in programming.","meta_title":"Beginners","meta_description":"Tutorials, articles, and tips to help beginners accelerate their journey in programming.","featureImageSharp":null},{"slug":"js","url":"https://backend.shahednasser.com/tag/js/","name":"Javascript","visibility":"public","feature_image":"https://backend.shahednasser.com/content/images/2022/01/photo-1592609931095-54a2168ae893-2.jpeg","description":"Learn more about Javascript through tutorials, articles, and tips.","meta_title":null,"meta_description":"Learn more about Javascript through tutorials, articles and tips.","featureImageSharp":null}],"plaintext":"This article was also published on Level Up Coding's gitconnected\n[https://levelup.gitconnected.com/chrome-extension-tutorial-replace-images-in-any-website-with-pikachu-de2a6e3548bb]\n\nWhat’s a better way to learn how to make a Chrome extension than making the web\ncuter with Pikachu images?\n\nIn this tutorial, I will show you how you can create a simple Chrome extension\nthat replaces images on websites with Pikachu images. We will discuss topics\nlike content scripts, background scripts, and messages between scripts in Chrome\nextensions.\n\nThe code for this tutorial is available here\n[https://github.com/shahednasser/pikachu-everywhere].\n\nFirst thing you need to do when creating any chrome extension is start with\ncreating a manifest.json file in the root of the extension’s directory. For now,\nthis file will hold only the following basic information about your extension:\n\nHere is what everything in this file means:\n\n 1. name: The name of the extension. I named the extension “Pikachu Everywhere”\n 2. version: This is the version of the extension. When you publish the\n    extension in the Chrome Web Store and you need to update it, you will have\n    to increase the version number so it’s good to start with a low number.\n 3. description: (Optional) Description of your extension\n 4. manifest_version: As of Chrome 18, developers are required to use manifest\n    version 2, since manifest version 1 is now deprecated.\n 5. icons: (Optional) Here we specify the extension’s icon. This icon will show\n    up in your browser’s toolbar, the Chrome Web Store, and any other place that\n    requires to show it. For that reason, it’s good to include different sizes\n    of the icon. I have used an icon from Free Icons PNG\n    [https://www.freeiconspng.com/img/17360] and resized the icons using \n    https://resizeimage.net/ (You can find the images in the GitHub repository\n    [https://github.com/shahednasser/pikachu-everywhere]). The paths specified\n    for these images is relative to the root of the extension.\n\nWith this, we have the core of any Chrome extension. Next, we’ll add the\nextension to the browser.\n\nGo to chrome://extensions. There, you can toggle developer mode at the top right\ncorner. Once you do that, a new toolbar will show up with three buttons: “Load\nunpacked,” “Pack extension,” and “Update.” Click on “Load unpacked” and choose\nyour extension’s directory.\n\nOnce you do that, you will see that your new chrome extension is now working.\nYes, it does nothing, but it’s working.\n\nIn Chrome extensions, there are two types of scripts you can use. There are\nBackground scripts and Content scripts. Background scripts run (obviously) in\nthe background. They are loaded when needed and unloaded when idle. They are\nused to listen to certain events in your Chrome extension.\n\nContent scripts are scripts loaded once you open a website and injected it into\nit. Once you open a website, they will start running just like any other script\non that website. After you close the website, the content scripts on that\nwebsite will stop running as well.\n\nFor our extension, we want to replace every image on every website with Pikachu\nimages. In order to do that we need to specify a content script that works every\ntime you open a web page.\n\nLet’s create our content script in assets/js/contentScript.js and include the\nfollowing script to test whether our extension is working or not:\n\nOne other thing we need to do is tell Chrome which script do we need to run as a\ncontent script. Add the following lines to manifest.json\n\nHere we are using content_scripts as key with the value as an array. Here’s what\neverything in the array means:\n\n 1. matches: here you can specify which URLs the content script should run on.\n    In our case we want our content script to run on all pages. So, we use the\n    placeholder “<all_urls>” to specify that.\n 2. all_frames: this key is used to allow the extension to specify if JavaScript\n    and CSS files should be injected into all frames matching the specified URL\n    requirements or only into the topmost frame in a tab.\n 3. js: here we specify the script we want to run as a content script. You can\n    specify more than one script, so the value has to be an array\n\nNow we’re ready to test our content script.\n\nBut before we do that we need to do one small step. In order to inform chrome\nthat we updated our chrome extension, we need to go back to chrome://extensions,\ngo to our extension, and press the reload icon.\n\nTo test if our content script is working, go to any web page you want, reload\nthe page if it was opened before, then right-click and press Inspect. In\nDevTools, open the Console tab. You will see in your console as expected:\n\nConsole of a web pageSo, we can verify that our content script is working. Try\nreloading the page, and the content script will execute again. Try opening\nanother web page, and the content script will execute on that page\nindependently.\n\nNow, we know how to inject a script on any web page, and through that script we\ncan do our work.\n\nIn our case, we need to replace every image in any website with random Pikachu\nimages. To do that, we will use this API\n[https://some-random-api.ml/img/pikachu] which will provide us with a JSON\nobject containing the link of a Pikachu image. Each request to that API will\nlook something like this:\n\nResult of API callWith the help of this API, the steps to achieve what we need\nwill be as follows:\n\n 1. Get all image elements on the web page.\n 2. Perform a GET request to the API to retrieve a random Pikachu image link.\n 3. Replace the image elements’ src attributes with the links we retrieve.\n\nThis all sounds good and easy, but there is one complication: content scripts in\nChrome extensions cannot perform Cross-Origin requests.\n\nSo how can we fetch the image URLs from the API? We will need to use a\nBackground script.\n\nAs we specified earlier, Background scripts run in the background in Chrome.\nThey are not dependent on any web page.\n\nScripts in Chrome extensions are isolated from each other. However, they share a\nmean of communication through the Chrome API\n[https://developer.chrome.com/extensions/api_index].\n\nWhat we will do is that we will listen for a message in the background script\nsent from content scripts. Every time a web page opens, our content script will\nrun, send a message to the background script requesting an image URL. The\nbackground script will then perform the asynchronous call to the Pikachu API,\nretrieve the link and send it back to the content script.\n\nThis may sound complicated at first, but it’s actually done in a very simple\nmanner.\n\nLet us first start by creating the background script and see it in action.\nCreate assets/js/background.js with the following content:\n\nNow, we need to tell Chrome that the file we just created will be our background\nscript. In order to do that, we need to go back to our manifest.json and add the\nfollowing:\n\nHere is what everything means:\n\n 1. scripts: An array that holds the paths of the scripts we will use as\n    background scripts. In our case, it’s just one.\n 2. persistent: should always be false unless the extension uses Chrome’s Web\n    Request API to block or modify network requests.\n\nNow, Chrome will know about our background script. It will load it when it’s\nneeded, and unload it when it becomes idle.\n\nTo test our background script, we need to reload our extension as we did\nearlier.\n\nOnce you do that, you will see a new link appear in your extension’s info box\nwith the text “inspect views background page”:\n\nIf you click on it, a new DevTool will open and in the console you will see:\n\nWe can now confirm that our background script is working. Even if you close any\nother web page or reload any web page, nothing will change in the background\nscript.\n\nLet’s go back to our objective again. We now need to listen to messages in our\nbackground script, and on receiving a new message fetch the URL from the Pikachu\nAPI.\n\nIn order to listen to messages, we will use the following method in Chrome’s\nAPI:\n\nWe need to pass a function to addListener. This function will be executed on\nreceiving any new message. The function takes three parameters:\n\n 1. message: the message sent of type any.\n 2. sender: of type MessageSender\n    [https://developer.chrome.com/extensions/runtime#type-MessageSender]\n 3. senderResponse: Callback function to call (at most once) when you have a\n    response. This function is sent by the sender on sending the message.\n\nSo this is what our background.js file should look like now:\n\nNow our background script is ready to receive messages, but there are no\nmessages being sent.\n\nAs we said earlier, each time a page opens, our content script will loop through\nimage elements in the web page, and send a message to the background script to\nfetch the Pikachu image link.\n\nIn order to send messages, we will need to use the following method from\nChrome’s API:\n\nThe parameter’s being sent are as follows:\n\n 1. extensionId: (Optional) the ID of the extension we are sending the message\n    to. If it’s omitted, the message will be sent to our own extension.\n 2. message: The message we are sending of type any.\n 3. options: Optional\n 4. responseCallback: The function to call after receiving the message. This is\n    the senderResponse parameter in the previous method we saw.\n\nSo, we will use this method in our content script to send a message to the\nbackground script to fetch the Pikachu URL from the API. Our content script\nshould now look like this:\n\nHere’s what we’re doing in the above code:\n\n 1. Line 1: get all image elements on the web page.\n 2. Line 2–6: Loop through the image elements. On each element, we send a\n    message to the background script. As you can tell, we are omitting the\n    optional extensionId and options parameters. The first parameter is the \n    message we are sending, and the second parameter is the callback function we\n    want the background to execute after it fetches the image’s link.\n\nWe are sending the object {msg: ‘image’, index: i} to our extension. This object\nhas two properties. The first one is to specify what our message is about. In\nour extension, it might not be very helpful, but when you have an extension that\nuses different types of messages, it’s a good idea to differentiate what each\nmessage is for. The second property is to specify the index of the image the\nlink is for in the images array. The reason behind this is that the callback\nfunction replacing the image will be called asynchronously, so i might point at\nanother index at the time it’s being executed.\n\nThe callback function receives an object that has two properties. data will be\nthe data received from the API call, and index will be the index of the image in\nthe array images. Once it’s called, it will set the image at index in images to\nthe link property is data.\n\nNow, we need to fetch the data from the API in our background script whenever\nthe content script sends a message. We can do this as follows:\n\nHere’s what’s going on here:\n\n 1. Line 1: Listen to messages in our extension\n 2. Line 2: Check if the message is to get the image URL. This will use the msg \n    attribute we passed when we sent the message in contentScript\n 3. Line 3–8: If the condition in Line 2 is true, fetch the data from the API.\n    In the first Promise we get the response text, then in the second Promise we\n    parse the JSON object and call senderResponse which is the callback function\n    specified by the sender of the message. We pass with it an object with the\n    parameters data (the data received through the API call) and index (the\n    index of the image, sent by the sender).\n 4. Line 9: simple handling of any error that might occur.\n 5. Line 10: If the sender specifies a callback function, it has to be called\n    before the listener stops executing or else it will throw an error. In our\n    case, we have to wait until we receive a response from the API which will\n    happen asynchronously, so we return true to specify that it will be called\n    asynchronously.\n\nOkay, our scripts are ready. Only one thing left — we need to give permission to\nthe API in our manifest.json:\n\nAll you need to do now is reload the extension in chrome://extensions, then open\nany page and see Pikachu everywhere!\n\nOf course, this extension will not replace background images. This can be done\nby looping through elements, checking if they have background images, and\nreplacing them the same way.","html":"<p><em>This article was also published on <a href=\"https://levelup.gitconnected.com/chrome-extension-tutorial-replace-images-in-any-website-with-pikachu-de2a6e3548bb\">Level Up Coding's gitconnected</a></em></p><p>What’s a better way to learn how to make a Chrome extension than making the web cuter with Pikachu images?</p><p>In this tutorial, I will show you how you can create a simple Chrome extension that replaces images on websites with Pikachu images. We will discuss topics like content scripts, background scripts, and messages between scripts in Chrome extensions.</p><p>The code for this tutorial is available <a href=\"https://github.com/shahednasser/pikachu-everywhere\" rel=\"noopener\">here</a>.</p><p>First thing you need to do when creating any chrome extension is start with creating a <strong><strong>manifest.json </strong></strong>file in the root of the extension’s directory. For now, this file will hold only the following basic information about your extension:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/6beec3aa60a2187e99e85479f8806c30.js\"></script><!--kg-card-end: html--><p>Here is what everything in this file means:</p><ol><li><strong><strong>name:</strong></strong> The name of the extension. I named the extension “Pikachu Everywhere”</li><li><strong><strong>version</strong></strong>: This is the version of the extension. When you publish the extension in the Chrome Web Store and you need to update it, you will have to increase the version number so it’s good to start with a low number.</li><li><strong><strong>description: (Optional) </strong></strong>Description of your extension</li><li><strong><strong>manifest_version</strong></strong>: As of Chrome 18, developers are required to use manifest version 2, since manifest version 1 is now deprecated.</li><li><strong><strong>icons: (Optional) </strong></strong>Here we specify the extension’s icon. This icon will show up in your browser’s toolbar, the Chrome Web Store, and any other place that requires to show it. For that reason, it’s good to include different sizes of the icon. I have used an icon from <a href=\"https://www.freeiconspng.com/img/17360\" rel=\"noopener\">Free Icons PNG</a> and resized the icons using <a href=\"https://resizeimage.net/\" rel=\"noopener\">https://resizeimage.net/</a> (You can find the images in the <a href=\"https://github.com/shahednasser/pikachu-everywhere\" rel=\"noopener\">GitHub repository</a>). The paths specified for these images is relative to the root of the extension.</li></ol><p>With this, we have the core of any Chrome extension. Next, we’ll add the extension to the browser.</p><p>Go to chrome://extensions. There, you can toggle developer mode at the top right corner. Once you do that, a new toolbar will show up with three buttons: “Load unpacked,” “Pack extension,” and “Update.” Click on “Load unpacked” and choose your extension’s directory.</p><p>Once you do that, you will see that your new chrome extension is now working. Yes, it does nothing, but it’s working.</p><p>In Chrome extensions, there are two types of scripts you can use. There are Background scripts and Content scripts. Background scripts run (obviously) in the background. They are loaded when needed and unloaded when idle. They are used to listen to certain events in your Chrome extension.</p><p>Content scripts are scripts loaded once you open a website and injected it into it. Once you open a website, they will start running just like any other script on that website. After you close the website, the content scripts on that website will stop running as well.</p><p>For our extension, we want to replace every image on every website with Pikachu images. In order to do that we need to specify a content script that works every time you open a web page.</p><p>Let’s create our content script in <code>assets/js/contentScript.js</code> and include the following script to test whether our extension is working or not:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/342ba17b0b6d715adaafd334a14416f9.js\"></script><!--kg-card-end: html--><p>One other thing we need to do is tell Chrome which script do we need to run as a content script. Add the following lines to <strong><strong>manifest.json</strong></strong></p><figure class=\"kg-card kg-embed-card\"><iframe src=\"https://levelup.gitconnected.com/media/d35d7df4566f532c2a0948ea540ee302\" allowfullscreen=\"\" frameborder=\"0\" height=\"0\" width=\"0\" title=\"adding content script to manifest.json\" class=\"t u v hm aj\" scrolling=\"auto\" style=\"box-sizing: inherit; position: absolute; top: 0px; left: 0px; width: 680px; height: 0px;\"></iframe></figure><p>Here we are using <code>content_scripts</code> as key with the value as an array. Here’s what everything in the array means:</p><ol><li><strong><strong>matches</strong></strong>: here you can specify which URLs the content script should run on. In our case we want our content script to run on all pages. So, we use the placeholder “&lt;all_urls&gt;” to specify that.</li><li><strong><strong>all_frames</strong></strong>: this key is used to allow the extension to specify if JavaScript and CSS files should be injected into all frames matching the specified URL requirements or only into the topmost frame in a tab.</li><li><strong><strong>js: </strong></strong>here we specify the script we want to run as a content script. You can specify more than one script, so the value has to be an array</li></ol><p>Now we’re ready to test our content script.</p><p>But before we do that we need to do one small step. In order to inform chrome that we updated our chrome extension, we need to go back to chrome://extensions, go to our extension, and press the reload icon.</p><p>To test if our content script is working, go to any web page you want, reload the page if it was opened before, then right-click and press Inspect. In DevTools, open the Console tab. You will see in your console as expected:</p><figure class=\"kg-card kg-image-card kg-card-hascaption\"><img src=\"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-1.png\" class=\"kg-image\" alt loading=\"lazy\"><figcaption>Console of a web page</figcaption></figure><p>So, we can verify that our content script is working. Try reloading the page, and the content script will execute again. Try opening another web page, and the content script will execute on that page independently.</p><p>Now, we know how to inject a script on any web page, and through that script we can do our work.</p><p>In our case, we need to replace every image in any website with random Pikachu images. To do that, we will use <a href=\"https://some-random-api.ml/img/pikachu\" rel=\"noopener\">this API</a> which will provide us with a JSON object containing the link of a Pikachu image. Each request to that API will look something like this:</p><figure class=\"kg-card kg-image-card kg-card-hascaption\"><img src=\"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-2.png\" class=\"kg-image\" alt loading=\"lazy\"><figcaption>Result of API call</figcaption></figure><p>With the help of this API, the steps to achieve what we need will be as follows:</p><ol><li>Get all image elements on the web page.</li><li>Perform a GET request to the API to retrieve a random Pikachu image link.</li><li>Replace the image elements’ <code>src</code> attributes with the links we retrieve.</li></ol><p>This all sounds good and easy, but there is one complication: content scripts in Chrome extensions cannot perform Cross-Origin requests.</p><p>So how can we fetch the image URLs from the API? We will need to use a Background script.</p><p>As we specified earlier, Background scripts run in the background in Chrome. They are not dependent on any web page.</p><p>Scripts in Chrome extensions are isolated from each other. However, they share a mean of communication through the <a href=\"https://developer.chrome.com/extensions/api_index\" rel=\"noopener\">Chrome API</a>.</p><p>What we will do is that we will listen for a message in the <strong><strong>background</strong></strong> script sent from <strong><strong>content</strong></strong> scripts. Every time a web page opens, our content script will run, send a message to the background script requesting an image URL. The background script will then perform the asynchronous call to the Pikachu API, retrieve the link and send it back to the content script.</p><p>This may sound complicated at first, but it’s actually done in a very simple manner.</p><p>Let us first start by creating the background script and see it in action. Create <code>assets/js/background.js</code> with the following content:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/b45de97a11eda346d1ea427b88c406f4.js\"></script><!--kg-card-end: html--><p>Now, we need to tell Chrome that the file we just created will be our background script. In order to do that, we need to go back to our <strong><strong>manifest.json</strong></strong> and add the following:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/c7a26cf5b3b2415110cb97e44f2b3834.js\"></script><!--kg-card-end: html--><p>Here is what everything means:</p><ol><li><strong><strong>scripts: </strong></strong>An array that holds the paths of the scripts we will use as background scripts. In our case, it’s just one.</li><li><strong><strong>persistent</strong></strong>: should always be false unless the extension uses Chrome’s Web Request API to block or modify network requests.</li></ol><p>Now, Chrome will know about our background script. It will load it when it’s needed, and unload it when it becomes idle.</p><p>To test our background script, we need to reload our extension as we did earlier.</p><p>Once you do that, you will see a new link appear in your extension’s info box with the text “inspect views background page”:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-5.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-3.png\" class=\"kg-image\" alt loading=\"lazy\"></figure><p>If you click on it, a new DevTool will open and in the console you will see:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-4.png\" class=\"kg-image\" alt loading=\"lazy\"></figure><p>We can now confirm that our background script is working. Even if you close any other web page or reload any web page, nothing will change in the background script.</p><p>Let’s go back to our objective again. We now need to listen to messages in our background script, and on receiving a new message fetch the URL from the Pikachu API.</p><p>In order to listen to messages, we will use the following method in Chrome’s API:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/4426ca477880552e4c563be8264b968c.js\"></script><!--kg-card-end: html--><p>We need to pass a function to <code>addListener</code>. This function will be executed on receiving any new message. The function takes three parameters:</p><ol><li><strong><strong>message: </strong></strong>the message sent of type any.</li><li><strong><strong>sender: </strong></strong>of type <a href=\"https://developer.chrome.com/extensions/runtime#type-MessageSender\" rel=\"noopener\">MessageSender</a></li><li><strong><strong>senderResponse: </strong></strong>Callback function to call (at most once) when you have a response. This function is sent by the sender on sending the message.</li></ol><p>So this is what our <strong><strong>background.js </strong></strong>file should look like now:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/4920b314274d2695b5ac0e771a4cd52c.js\"></script><!--kg-card-end: html--><p>Now our background script is ready to receive messages, but there are no messages being sent.</p><p>As we said earlier, each time a page opens, our content script will loop through image elements in the web page, and send a message to the background script to fetch the Pikachu image link.</p><p>In order to send messages, we will need to use the following method from Chrome’s API:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/03e371015982ef271518922e56139c19.js\"></script><!--kg-card-end: html--><p>The parameter’s being sent are as follows:</p><ol><li><strong><strong>extensionId: (Optional) </strong></strong>the ID of the extension we are sending the message to. If it’s omitted, the message will be sent to our own extension.</li><li><strong><strong>message:</strong></strong> The message we are sending of type any.</li><li><strong><strong>options: Optional</strong></strong></li><li><strong><strong>responseCallback: </strong></strong>The function to call after receiving the message. This is the <strong><strong>senderResponse</strong></strong> parameter in the previous method we saw.</li></ol><p>So, we will use this method in our content script to send a message to the background script to fetch the Pikachu URL from the API. Our content script should now look like this:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/bd4051325006a5f3ca01e882b51eebc5.js\"></script><!--kg-card-end: html--><p>Here’s what we’re doing in the above code:</p><ol><li><strong><strong>Line 1: </strong></strong>get all image elements on the web page.</li><li><strong><strong>Line 2–6: </strong></strong>Loop through the image elements. On each element, we send a message to the background script. As you can tell, we are omitting the optional <strong><strong>extensionId </strong></strong>and <strong><strong>options</strong></strong> parameters. The first parameter is the <strong><strong>message </strong></strong>we are sending, and the second parameter is the callback function we want the background to execute after it fetches the image’s link.</li></ol><p>We are sending the object <strong><strong>{msg: ‘image’, index: i}</strong></strong> to our extension. This object has two properties. The first one is to specify what our message is about. In our extension, it might not be very helpful, but when you have an extension that uses different types of messages, it’s a good idea to differentiate what each message is for. The second property is to specify the index of the image the link is for in the <strong><strong>images</strong></strong> array. The reason behind this is that the callback function replacing the image will be called asynchronously, so <strong><strong>i </strong></strong>might point at another index at the time it’s being executed.</p><p>The callback function receives an object that has two properties. <strong><strong>data</strong></strong> will be the data received from the API call, and <strong><strong>index</strong></strong> will be the index of the image in the array <strong><strong>images</strong></strong>. Once it’s called, it will set the image at <strong><strong>index</strong></strong> in <strong><strong>images</strong></strong> to the link property is <strong><strong>data</strong></strong>.</p><p>Now, we need to fetch the data from the API in our background script whenever the content script sends a message. We can do this as follows:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/9c024a8b40396e7c6a6ae1250fb5d94d.js\"></script><!--kg-card-end: html--><p>Here’s what’s going on here:</p><ol><li><strong><strong>Line 1:</strong></strong> Listen to messages in our extension</li><li><strong><strong>Line 2: </strong></strong>Check if the message is to get the image URL. This will use the <strong><strong>msg </strong></strong>attribute we passed when we sent the message in <strong><strong>contentScript</strong></strong></li><li><strong><strong>Line 3–8:</strong></strong> If the condition in <strong><strong>Line 2</strong></strong> is true, fetch the data from the API. In the first <code>Promise</code> we get the response text, then in the second <code>Promise</code> we parse the JSON object and call <strong><strong>senderResponse</strong></strong> which is the callback function specified by the sender of the message. We pass with it an object with the parameters <strong><strong>data </strong></strong>(the data received through the API call) and <strong><strong>index</strong></strong> (the index of the image, sent by the sender).</li><li><strong><strong>Line 9: </strong></strong>simple handling of any error that might occur.</li><li><strong><strong>Line 10</strong></strong>: If the sender specifies a callback function, it has to be called before the listener stops executing or else it will throw an error. In our case, we have to wait until we receive a response from the API which will happen asynchronously, so we return true to specify that it will be called asynchronously.</li></ol><p>Okay, our scripts are ready. Only one thing left — we need to give permission to the API in our <strong><strong>manifest.json:</strong></strong></p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/8d6786f1583a91fe31635715caf44b0c.js\"></script><!--kg-card-end: html--><p>All you need to do now is reload the extension in chrome://extensions, then open any page and see Pikachu everywhere!</p><p>Of course, this extension will not replace background images. This can be done by looping through elements, checking if they have background images, and replacing them the same way.</p>","url":"https://backend.shahednasser.com/chrome-extension-tutorial-replace-images-in-any-website-with-pikachu/","canonical_url":null,"uuid":"d3c062c3-8b05-4b63-919c-4fbbcdb59cc3","codeinjection_foot":null,"codeinjection_head":null,"codeinjection_styles":null,"comment_id":"5fa596aabc1317001e675bff","reading_time":9,"send_email_when_published":null,"email_subject":null,"childHtmlRehype":{"html":"<p><em>This article was also published on <a href=\"https://levelup.gitconnected.com/chrome-extension-tutorial-replace-images-in-any-website-with-pikachu-de2a6e3548bb\">Level Up Coding's gitconnected</a></em></p><p>What’s a better way to learn how to make a Chrome extension than making the web cuter with Pikachu images?</p><p>In this tutorial, I will show you how you can create a simple Chrome extension that replaces images on websites with Pikachu images. We will discuss topics like content scripts, background scripts, and messages between scripts in Chrome extensions.</p><p>The code for this tutorial is available <a href=\"https://github.com/shahednasser/pikachu-everywhere\" rel=\"noopener\">here</a>.</p><p>First thing you need to do when creating any chrome extension is start with creating a <strong><strong>manifest.json </strong></strong>file in the root of the extension’s directory. For now, this file will hold only the following basic information about your extension:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/6beec3aa60a2187e99e85479f8806c30.js\"></script><!--kg-card-end: html--><p>Here is what everything in this file means:</p><ol><li><strong><strong>name:</strong></strong> The name of the extension. I named the extension “Pikachu Everywhere”</li><li><strong><strong>version</strong></strong>: This is the version of the extension. When you publish the extension in the Chrome Web Store and you need to update it, you will have to increase the version number so it’s good to start with a low number.</li><li><strong><strong>description: (Optional) </strong></strong>Description of your extension</li><li><strong><strong>manifest_version</strong></strong>: As of Chrome 18, developers are required to use manifest version 2, since manifest version 1 is now deprecated.</li><li><strong><strong>icons: (Optional) </strong></strong>Here we specify the extension’s icon. This icon will show up in your browser’s toolbar, the Chrome Web Store, and any other place that requires to show it. For that reason, it’s good to include different sizes of the icon. I have used an icon from <a href=\"https://www.freeiconspng.com/img/17360\" rel=\"noopener\">Free Icons PNG</a> and resized the icons using <a href=\"https://resizeimage.net/\" rel=\"noopener\">https://resizeimage.net/</a> (You can find the images in the <a href=\"https://github.com/shahednasser/pikachu-everywhere\" rel=\"noopener\">GitHub repository</a>). The paths specified for these images is relative to the root of the extension.</li></ol><p>With this, we have the core of any Chrome extension. Next, we’ll add the extension to the browser.</p><p>Go to chrome://extensions. There, you can toggle developer mode at the top right corner. Once you do that, a new toolbar will show up with three buttons: “Load unpacked,” “Pack extension,” and “Update.” Click on “Load unpacked” and choose your extension’s directory.</p><p>Once you do that, you will see that your new chrome extension is now working. Yes, it does nothing, but it’s working.</p><p>In Chrome extensions, there are two types of scripts you can use. There are Background scripts and Content scripts. Background scripts run (obviously) in the background. They are loaded when needed and unloaded when idle. They are used to listen to certain events in your Chrome extension.</p><p>Content scripts are scripts loaded once you open a website and injected it into it. Once you open a website, they will start running just like any other script on that website. After you close the website, the content scripts on that website will stop running as well.</p><p>For our extension, we want to replace every image on every website with Pikachu images. In order to do that we need to specify a content script that works every time you open a web page.</p><p>Let’s create our content script in <code class=\"language-text\">assets/js/contentScript.js</code> and include the following script to test whether our extension is working or not:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/342ba17b0b6d715adaafd334a14416f9.js\"></script><!--kg-card-end: html--><p>One other thing we need to do is tell Chrome which script do we need to run as a content script. Add the following lines to <strong><strong>manifest.json</strong></strong></p><figure class=\"kg-card kg-embed-card\"><iframe src=\"https://levelup.gitconnected.com/media/d35d7df4566f532c2a0948ea540ee302\" allowfullscreen frameborder=\"0\" height=\"0\" width=\"0\" title=\"adding content script to manifest.json\" class=\"t u v hm aj\" scrolling=\"auto\" style=\"box-sizing: inherit; position: absolute; top: 0px; left: 0px; width: 680px; height: 0px;\"></iframe></figure><p>Here we are using <code class=\"language-text\">content_scripts</code> as key with the value as an array. Here’s what everything in the array means:</p><ol><li><strong><strong>matches</strong></strong>: here you can specify which URLs the content script should run on. In our case we want our content script to run on all pages. So, we use the placeholder “&#x3C;all_urls>” to specify that.</li><li><strong><strong>all_frames</strong></strong>: this key is used to allow the extension to specify if JavaScript and CSS files should be injected into all frames matching the specified URL requirements or only into the topmost frame in a tab.</li><li><strong><strong>js: </strong></strong>here we specify the script we want to run as a content script. You can specify more than one script, so the value has to be an array</li></ol><p>Now we’re ready to test our content script.</p><p>But before we do that we need to do one small step. In order to inform chrome that we updated our chrome extension, we need to go back to chrome://extensions, go to our extension, and press the reload icon.</p><p>To test if our content script is working, go to any web page you want, reload the page if it was opened before, then right-click and press Inspect. In DevTools, open the Console tab. You will see in your console as expected:</p><figure class=\"kg-card kg-image-card kg-card-hascaption\"><img src=\"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-1.png\" class=\"kg-image\" alt=\"\" loading=\"lazy\"><figcaption>Console of a web page</figcaption></figure><p>So, we can verify that our content script is working. Try reloading the page, and the content script will execute again. Try opening another web page, and the content script will execute on that page independently.</p><p>Now, we know how to inject a script on any web page, and through that script we can do our work.</p><p>In our case, we need to replace every image in any website with random Pikachu images. To do that, we will use <a href=\"https://some-random-api.ml/img/pikachu\" rel=\"noopener\">this API</a> which will provide us with a JSON object containing the link of a Pikachu image. Each request to that API will look something like this:</p><figure class=\"kg-card kg-image-card kg-card-hascaption\"><img src=\"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-2.png\" class=\"kg-image\" alt=\"\" loading=\"lazy\"><figcaption>Result of API call</figcaption></figure><p>With the help of this API, the steps to achieve what we need will be as follows:</p><ol><li>Get all image elements on the web page.</li><li>Perform a GET request to the API to retrieve a random Pikachu image link.</li><li>Replace the image elements’ <code class=\"language-text\">src</code> attributes with the links we retrieve.</li></ol><p>This all sounds good and easy, but there is one complication: content scripts in Chrome extensions cannot perform Cross-Origin requests.</p><p>So how can we fetch the image URLs from the API? We will need to use a Background script.</p><p>As we specified earlier, Background scripts run in the background in Chrome. They are not dependent on any web page.</p><p>Scripts in Chrome extensions are isolated from each other. However, they share a mean of communication through the <a href=\"https://developer.chrome.com/extensions/api_index\" rel=\"noopener\">Chrome API</a>.</p><p>What we will do is that we will listen for a message in the <strong><strong>background</strong></strong> script sent from <strong><strong>content</strong></strong> scripts. Every time a web page opens, our content script will run, send a message to the background script requesting an image URL. The background script will then perform the asynchronous call to the Pikachu API, retrieve the link and send it back to the content script.</p><p>This may sound complicated at first, but it’s actually done in a very simple manner.</p><p>Let us first start by creating the background script and see it in action. Create <code class=\"language-text\">assets/js/background.js</code> with the following content:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/b45de97a11eda346d1ea427b88c406f4.js\"></script><!--kg-card-end: html--><p>Now, we need to tell Chrome that the file we just created will be our background script. In order to do that, we need to go back to our <strong><strong>manifest.json</strong></strong> and add the following:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/c7a26cf5b3b2415110cb97e44f2b3834.js\"></script><!--kg-card-end: html--><p>Here is what everything means:</p><ol><li><strong><strong>scripts: </strong></strong>An array that holds the paths of the scripts we will use as background scripts. In our case, it’s just one.</li><li><strong><strong>persistent</strong></strong>: should always be false unless the extension uses Chrome’s Web Request API to block or modify network requests.</li></ol><p>Now, Chrome will know about our background script. It will load it when it’s needed, and unload it when it becomes idle.</p><p>To test our background script, we need to reload our extension as we did earlier.</p><p>Once you do that, you will see a new link appear in your extension’s info box with the text “inspect views background page”:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-5.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-3.png\" class=\"kg-image\" alt=\"\" loading=\"lazy\"></figure><p>If you click on it, a new DevTool will open and in the console you will see:</p><figure class=\"kg-card kg-image-card\"><img src=\"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-4.png\" class=\"kg-image\" alt=\"\" loading=\"lazy\"></figure><p>We can now confirm that our background script is working. Even if you close any other web page or reload any web page, nothing will change in the background script.</p><p>Let’s go back to our objective again. We now need to listen to messages in our background script, and on receiving a new message fetch the URL from the Pikachu API.</p><p>In order to listen to messages, we will use the following method in Chrome’s API:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/4426ca477880552e4c563be8264b968c.js\"></script><!--kg-card-end: html--><p>We need to pass a function to <code class=\"language-text\">addListener</code>. This function will be executed on receiving any new message. The function takes three parameters:</p><ol><li><strong><strong>message: </strong></strong>the message sent of type any.</li><li><strong><strong>sender: </strong></strong>of type <a href=\"https://developer.chrome.com/extensions/runtime#type-MessageSender\" rel=\"noopener\">MessageSender</a></li><li><strong><strong>senderResponse: </strong></strong>Callback function to call (at most once) when you have a response. This function is sent by the sender on sending the message.</li></ol><p>So this is what our <strong><strong>background.js </strong></strong>file should look like now:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/4920b314274d2695b5ac0e771a4cd52c.js\"></script><!--kg-card-end: html--><p>Now our background script is ready to receive messages, but there are no messages being sent.</p><p>As we said earlier, each time a page opens, our content script will loop through image elements in the web page, and send a message to the background script to fetch the Pikachu image link.</p><p>In order to send messages, we will need to use the following method from Chrome’s API:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/03e371015982ef271518922e56139c19.js\"></script><!--kg-card-end: html--><p>The parameter’s being sent are as follows:</p><ol><li><strong><strong>extensionId: (Optional) </strong></strong>the ID of the extension we are sending the message to. If it’s omitted, the message will be sent to our own extension.</li><li><strong><strong>message:</strong></strong> The message we are sending of type any.</li><li><strong><strong>options: Optional</strong></strong></li><li><strong><strong>responseCallback: </strong></strong>The function to call after receiving the message. This is the <strong><strong>senderResponse</strong></strong> parameter in the previous method we saw.</li></ol><p>So, we will use this method in our content script to send a message to the background script to fetch the Pikachu URL from the API. Our content script should now look like this:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/bd4051325006a5f3ca01e882b51eebc5.js\"></script><!--kg-card-end: html--><p>Here’s what we’re doing in the above code:</p><ol><li><strong><strong>Line 1: </strong></strong>get all image elements on the web page.</li><li><strong><strong>Line 2–6: </strong></strong>Loop through the image elements. On each element, we send a message to the background script. As you can tell, we are omitting the optional <strong><strong>extensionId </strong></strong>and <strong><strong>options</strong></strong> parameters. The first parameter is the <strong><strong>message </strong></strong>we are sending, and the second parameter is the callback function we want the background to execute after it fetches the image’s link.</li></ol><p>We are sending the object <strong><strong>{msg: ‘image’, index: i}</strong></strong> to our extension. This object has two properties. The first one is to specify what our message is about. In our extension, it might not be very helpful, but when you have an extension that uses different types of messages, it’s a good idea to differentiate what each message is for. The second property is to specify the index of the image the link is for in the <strong><strong>images</strong></strong> array. The reason behind this is that the callback function replacing the image will be called asynchronously, so <strong><strong>i </strong></strong>might point at another index at the time it’s being executed.</p><p>The callback function receives an object that has two properties. <strong><strong>data</strong></strong> will be the data received from the API call, and <strong><strong>index</strong></strong> will be the index of the image in the array <strong><strong>images</strong></strong>. Once it’s called, it will set the image at <strong><strong>index</strong></strong> in <strong><strong>images</strong></strong> to the link property is <strong><strong>data</strong></strong>.</p><p>Now, we need to fetch the data from the API in our background script whenever the content script sends a message. We can do this as follows:</p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/9c024a8b40396e7c6a6ae1250fb5d94d.js\"></script><!--kg-card-end: html--><p>Here’s what’s going on here:</p><ol><li><strong><strong>Line 1:</strong></strong> Listen to messages in our extension</li><li><strong><strong>Line 2: </strong></strong>Check if the message is to get the image URL. This will use the <strong><strong>msg </strong></strong>attribute we passed when we sent the message in <strong><strong>contentScript</strong></strong></li><li><strong><strong>Line 3–8:</strong></strong> If the condition in <strong><strong>Line 2</strong></strong> is true, fetch the data from the API. In the first <code class=\"language-text\">Promise</code> we get the response text, then in the second <code class=\"language-text\">Promise</code> we parse the JSON object and call <strong><strong>senderResponse</strong></strong> which is the callback function specified by the sender of the message. We pass with it an object with the parameters <strong><strong>data </strong></strong>(the data received through the API call) and <strong><strong>index</strong></strong> (the index of the image, sent by the sender).</li><li><strong><strong>Line 9: </strong></strong>simple handling of any error that might occur.</li><li><strong><strong>Line 10</strong></strong>: If the sender specifies a callback function, it has to be called before the listener stops executing or else it will throw an error. In our case, we have to wait until we receive a response from the API which will happen asynchronously, so we return true to specify that it will be called asynchronously.</li></ol><p>Okay, our scripts are ready. Only one thing left — we need to give permission to the API in our <strong><strong>manifest.json:</strong></strong></p><!--kg-card-begin: html--><script src=\"https://gist.github.com/shahednasser/8d6786f1583a91fe31635715caf44b0c.js\"></script><!--kg-card-end: html--><p>All you need to do now is reload the extension in chrome://extensions, then open any page and see Pikachu everywhere!</p><p>Of course, this extension will not replace background images. This can be done by looping through elements, checking if they have background images, and replacing them the same way.</p>","htmlAst":{"type":"root","children":[{"type":"element","tagName":"p","properties":{},"children":[{"type":"element","tagName":"em","properties":{},"children":[{"type":"text","value":"This article was also published on "},{"type":"element","tagName":"a","properties":{"href":"https://levelup.gitconnected.com/chrome-extension-tutorial-replace-images-in-any-website-with-pikachu-de2a6e3548bb"},"children":[{"type":"text","value":"Level Up Coding's gitconnected"}]}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What’s a better way to learn how to make a Chrome extension than making the web cuter with Pikachu images?"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In this tutorial, I will show you how you can create a simple Chrome extension that replaces images on websites with Pikachu images. We will discuss topics like content scripts, background scripts, and messages between scripts in Chrome extensions."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The code for this tutorial is available "},{"type":"element","tagName":"a","properties":{"href":"https://github.com/shahednasser/pikachu-everywhere","rel":["noopener"]},"children":[{"type":"text","value":"here"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"First thing you need to do when creating any chrome extension is start with creating a "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"manifest.json "}]}]},{"type":"text","value":"file in the root of the extension’s directory. For now, this file will hold only the following basic information about your extension:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/6beec3aa60a2187e99e85479f8806c30.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here is what everything in this file means:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"name:"}]}]},{"type":"text","value":" The name of the extension. I named the extension “Pikachu Everywhere”"}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"version"}]}]},{"type":"text","value":": This is the version of the extension. When you publish the extension in the Chrome Web Store and you need to update it, you will have to increase the version number so it’s good to start with a low number."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"description: (Optional) "}]}]},{"type":"text","value":"Description of your extension"}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"manifest_version"}]}]},{"type":"text","value":": As of Chrome 18, developers are required to use manifest version 2, since manifest version 1 is now deprecated."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"icons: (Optional) "}]}]},{"type":"text","value":"Here we specify the extension’s icon. This icon will show up in your browser’s toolbar, the Chrome Web Store, and any other place that requires to show it. For that reason, it’s good to include different sizes of the icon. I have used an icon from "},{"type":"element","tagName":"a","properties":{"href":"https://www.freeiconspng.com/img/17360","rel":["noopener"]},"children":[{"type":"text","value":"Free Icons PNG"}]},{"type":"text","value":" and resized the icons using "},{"type":"element","tagName":"a","properties":{"href":"https://resizeimage.net/","rel":["noopener"]},"children":[{"type":"text","value":"https://resizeimage.net/"}]},{"type":"text","value":" (You can find the images in the "},{"type":"element","tagName":"a","properties":{"href":"https://github.com/shahednasser/pikachu-everywhere","rel":["noopener"]},"children":[{"type":"text","value":"GitHub repository"}]},{"type":"text","value":"). The paths specified for these images is relative to the root of the extension."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"With this, we have the core of any Chrome extension. Next, we’ll add the extension to the browser."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Go to chrome://extensions. There, you can toggle developer mode at the top right corner. Once you do that, a new toolbar will show up with three buttons: “Load unpacked,” “Pack extension,” and “Update.” Click on “Load unpacked” and choose your extension’s directory."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Once you do that, you will see that your new chrome extension is now working. Yes, it does nothing, but it’s working."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In Chrome extensions, there are two types of scripts you can use. There are Background scripts and Content scripts. Background scripts run (obviously) in the background. They are loaded when needed and unloaded when idle. They are used to listen to certain events in your Chrome extension."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Content scripts are scripts loaded once you open a website and injected it into it. Once you open a website, they will start running just like any other script on that website. After you close the website, the content scripts on that website will stop running as well."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"For our extension, we want to replace every image on every website with Pikachu images. In order to do that we need to specify a content script that works every time you open a web page."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s create our content script in "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"assets/js/contentScript.js"}]},{"type":"text","value":" and include the following script to test whether our extension is working or not:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/342ba17b0b6d715adaafd334a14416f9.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"One other thing we need to do is tell Chrome which script do we need to run as a content script. Add the following lines to "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"manifest.json"}]}]}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-embed-card"]},"children":[{"type":"element","tagName":"iframe","properties":{"src":"https://levelup.gitconnected.com/media/d35d7df4566f532c2a0948ea540ee302","allowFullScreen":true,"frameBorder":"0","height":0,"width":0,"title":"adding content script to manifest.json","className":["t","u","v","hm","aj"],"scrolling":"auto","style":"box-sizing: inherit; position: absolute; top: 0px; left: 0px; width: 680px; height: 0px;"},"children":[]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here we are using "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"content_scripts"}]},{"type":"text","value":" as key with the value as an array. Here’s what everything in the array means:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"matches"}]}]},{"type":"text","value":": here you can specify which URLs the content script should run on. In our case we want our content script to run on all pages. So, we use the placeholder “<all_urls>” to specify that."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"all_frames"}]}]},{"type":"text","value":": this key is used to allow the extension to specify if JavaScript and CSS files should be injected into all frames matching the specified URL requirements or only into the topmost frame in a tab."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"js: "}]}]},{"type":"text","value":"here we specify the script we want to run as a content script. You can specify more than one script, so the value has to be an array"}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now we’re ready to test our content script."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"But before we do that we need to do one small step. In order to inform chrome that we updated our chrome extension, we need to go back to chrome://extensions, go to our extension, and press the reload icon."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"To test if our content script is working, go to any web page you want, reload the page if it was opened before, then right-click and press Inspect. In DevTools, open the Console tab. You will see in your console as expected:"}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-image-card","kg-card-hascaption"]},"children":[{"type":"element","tagName":"img","properties":{"src":"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-1.png","className":["kg-image"],"alt":"","loading":"lazy"},"children":[]},{"type":"element","tagName":"figcaption","properties":{},"children":[{"type":"text","value":"Console of a web page"}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"So, we can verify that our content script is working. Try reloading the page, and the content script will execute again. Try opening another web page, and the content script will execute on that page independently."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we know how to inject a script on any web page, and through that script we can do our work."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In our case, we need to replace every image in any website with random Pikachu images. To do that, we will use "},{"type":"element","tagName":"a","properties":{"href":"https://some-random-api.ml/img/pikachu","rel":["noopener"]},"children":[{"type":"text","value":"this API"}]},{"type":"text","value":" which will provide us with a JSON object containing the link of a Pikachu image. Each request to that API will look something like this:"}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-image-card","kg-card-hascaption"]},"children":[{"type":"element","tagName":"img","properties":{"src":"https://res-3.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-2.png","className":["kg-image"],"alt":"","loading":"lazy"},"children":[]},{"type":"element","tagName":"figcaption","properties":{},"children":[{"type":"text","value":"Result of API call"}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"With the help of this API, the steps to achieve what we need will be as follows:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Get all image elements on the web page."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Perform a GET request to the API to retrieve a random Pikachu image link."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"text","value":"Replace the image elements’ "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"src"}]},{"type":"text","value":" attributes with the links we retrieve."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This all sounds good and easy, but there is one complication: content scripts in Chrome extensions cannot perform Cross-Origin requests."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"So how can we fetch the image URLs from the API? We will need to use a Background script."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"As we specified earlier, Background scripts run in the background in Chrome. They are not dependent on any web page."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Scripts in Chrome extensions are isolated from each other. However, they share a mean of communication through the "},{"type":"element","tagName":"a","properties":{"href":"https://developer.chrome.com/extensions/api_index","rel":["noopener"]},"children":[{"type":"text","value":"Chrome API"}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"What we will do is that we will listen for a message in the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"background"}]}]},{"type":"text","value":" script sent from "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"content"}]}]},{"type":"text","value":" scripts. Every time a web page opens, our content script will run, send a message to the background script requesting an image URL. The background script will then perform the asynchronous call to the Pikachu API, retrieve the link and send it back to the content script."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"This may sound complicated at first, but it’s actually done in a very simple manner."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let us first start by creating the background script and see it in action. Create "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"assets/js/background.js"}]},{"type":"text","value":" with the following content:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/b45de97a11eda346d1ea427b88c406f4.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we need to tell Chrome that the file we just created will be our background script. In order to do that, we need to go back to our "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"manifest.json"}]}]},{"type":"text","value":" and add the following:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/c7a26cf5b3b2415110cb97e44f2b3834.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here is what everything means:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"scripts: "}]}]},{"type":"text","value":"An array that holds the paths of the scripts we will use as background scripts. In our case, it’s just one."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"persistent"}]}]},{"type":"text","value":": should always be false unless the extension uses Chrome’s Web Request API to block or modify network requests."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, Chrome will know about our background script. It will load it when it’s needed, and unload it when it becomes idle."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"To test our background script, we need to reload our extension as we did earlier."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Once you do that, you will see a new link appear in your extension’s info box with the text “inspect views background page”:"}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-image-card"]},"children":[{"type":"element","tagName":"img","properties":{"src":"https://res-5.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-3.png","className":["kg-image"],"alt":"","loading":"lazy"},"children":[]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"If you click on it, a new DevTool will open and in the console you will see:"}]},{"type":"element","tagName":"figure","properties":{"className":["kg-card","kg-image-card"]},"children":[{"type":"element","tagName":"img","properties":{"src":"https://res-4.cloudinary.com/hbqmf3mbz/image/upload/q_auto/v1/ghost-blog-images/chrome-extension-screenshot-4.png","className":["kg-image"],"alt":"","loading":"lazy"},"children":[]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We can now confirm that our background script is working. Even if you close any other web page or reload any web page, nothing will change in the background script."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Let’s go back to our objective again. We now need to listen to messages in our background script, and on receiving a new message fetch the URL from the Pikachu API."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In order to listen to messages, we will use the following method in Chrome’s API:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/4426ca477880552e4c563be8264b968c.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We need to pass a function to "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"addListener"}]},{"type":"text","value":". This function will be executed on receiving any new message. The function takes three parameters:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"message: "}]}]},{"type":"text","value":"the message sent of type any."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"sender: "}]}]},{"type":"text","value":"of type "},{"type":"element","tagName":"a","properties":{"href":"https://developer.chrome.com/extensions/runtime#type-MessageSender","rel":["noopener"]},"children":[{"type":"text","value":"MessageSender"}]}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"senderResponse: "}]}]},{"type":"text","value":"Callback function to call (at most once) when you have a response. This function is sent by the sender on sending the message."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"So this is what our "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"background.js "}]}]},{"type":"text","value":"file should look like now:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/4920b314274d2695b5ac0e771a4cd52c.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now our background script is ready to receive messages, but there are no messages being sent."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"As we said earlier, each time a page opens, our content script will loop through image elements in the web page, and send a message to the background script to fetch the Pikachu image link."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"In order to send messages, we will need to use the following method from Chrome’s API:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/03e371015982ef271518922e56139c19.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The parameter’s being sent are as follows:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"extensionId: (Optional) "}]}]},{"type":"text","value":"the ID of the extension we are sending the message to. If it’s omitted, the message will be sent to our own extension."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"message:"}]}]},{"type":"text","value":" The message we are sending of type any."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"options: Optional"}]}]}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"responseCallback: "}]}]},{"type":"text","value":"The function to call after receiving the message. This is the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"senderResponse"}]}]},{"type":"text","value":" parameter in the previous method we saw."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"So, we will use this method in our content script to send a message to the background script to fetch the Pikachu URL from the API. Our content script should now look like this:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/bd4051325006a5f3ca01e882b51eebc5.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here’s what we’re doing in the above code:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 1: "}]}]},{"type":"text","value":"get all image elements on the web page."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 2–6: "}]}]},{"type":"text","value":"Loop through the image elements. On each element, we send a message to the background script. As you can tell, we are omitting the optional "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"extensionId "}]}]},{"type":"text","value":"and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"options"}]}]},{"type":"text","value":" parameters. The first parameter is the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"message "}]}]},{"type":"text","value":"we are sending, and the second parameter is the callback function we want the background to execute after it fetches the image’s link."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"We are sending the object "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"{msg: ‘image’, index: i}"}]}]},{"type":"text","value":" to our extension. This object has two properties. The first one is to specify what our message is about. In our extension, it might not be very helpful, but when you have an extension that uses different types of messages, it’s a good idea to differentiate what each message is for. The second property is to specify the index of the image the link is for in the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"images"}]}]},{"type":"text","value":" array. The reason behind this is that the callback function replacing the image will be called asynchronously, so "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"i "}]}]},{"type":"text","value":"might point at another index at the time it’s being executed."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"The callback function receives an object that has two properties. "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"data"}]}]},{"type":"text","value":" will be the data received from the API call, and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index"}]}]},{"type":"text","value":" will be the index of the image in the array "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"images"}]}]},{"type":"text","value":". Once it’s called, it will set the image at "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index"}]}]},{"type":"text","value":" in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"images"}]}]},{"type":"text","value":" to the link property is "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"data"}]}]},{"type":"text","value":"."}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Now, we need to fetch the data from the API in our background script whenever the content script sends a message. We can do this as follows:"}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/9c024a8b40396e7c6a6ae1250fb5d94d.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Here’s what’s going on here:"}]},{"type":"element","tagName":"ol","properties":{},"children":[{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 1:"}]}]},{"type":"text","value":" Listen to messages in our extension"}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 2: "}]}]},{"type":"text","value":"Check if the message is to get the image URL. This will use the "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"msg "}]}]},{"type":"text","value":"attribute we passed when we sent the message in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"contentScript"}]}]}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 3–8:"}]}]},{"type":"text","value":" If the condition in "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 2"}]}]},{"type":"text","value":" is true, fetch the data from the API. In the first "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Promise"}]},{"type":"text","value":" we get the response text, then in the second "},{"type":"element","tagName":"code","properties":{"className":["language-text"]},"children":[{"type":"text","value":"Promise"}]},{"type":"text","value":" we parse the JSON object and call "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"senderResponse"}]}]},{"type":"text","value":" which is the callback function specified by the sender of the message. We pass with it an object with the parameters "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"data "}]}]},{"type":"text","value":"(the data received through the API call) and "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"index"}]}]},{"type":"text","value":" (the index of the image, sent by the sender)."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 9: "}]}]},{"type":"text","value":"simple handling of any error that might occur."}]},{"type":"element","tagName":"li","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"Line 10"}]}]},{"type":"text","value":": If the sender specifies a callback function, it has to be called before the listener stops executing or else it will throw an error. In our case, we have to wait until we receive a response from the API which will happen asynchronously, so we return true to specify that it will be called asynchronously."}]}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Okay, our scripts are ready. Only one thing left — we need to give permission to the API in our "},{"type":"element","tagName":"strong","properties":{},"children":[{"type":"element","tagName":"strong","properties":{},"children":[{"type":"text","value":"manifest.json:"}]}]}]},{"type":"comment","value":"kg-card-begin: html"},{"type":"element","tagName":"script","properties":{"src":"https://gist.github.com/shahednasser/8d6786f1583a91fe31635715caf44b0c.js"},"children":[]},{"type":"comment","value":"kg-card-end: html"},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"All you need to do now is reload the extension in chrome://extensions, then open any page and see Pikachu everywhere!"}]},{"type":"element","tagName":"p","properties":{},"children":[{"type":"text","value":"Of course, this extension will not replace background images. This can be done by looping through elements, checking if they have background images, and replacing them the same way."}]}],"data":{"quirksMode":false}},"tableOfContents":[]},"featureImageSharp":{"base":"chrome-extension.gif","publicURL":"/static/498b0f8235a6b5cc5d72fd2244922304/chrome-extension.gif","imageMeta":{"width":500,"height":309},"childImageSharp":null}},"allGhostPost":{"edges":[]}},"pageContext":{"slug":"react-hooks-tutorial-create-a-number-trivia-generator-website","prev":"css-variables-and-how-to-use-them","next":"chrome-extension-tutorial-replace-images-in-any-website-with-pikachu","tag":"","limit":3,"skip":0,"primaryTagCount":0,"collectionPaths":{}}},"staticQueryHashes":["1272700106","1676991999","2138873178","2546165603","2681841279","2938721187","293880488","3052966952","4156497161"]}