<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Antony Sande on Medium]]></title>
        <description><![CDATA[Stories by Antony Sande on Medium]]></description>
        <link>https://medium.com/@sandeantony?source=rss-8885f7052217------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lJN-eS3AgbkJWGoTCs4Qlg.jpeg</url>
            <title>Stories by Antony Sande on Medium</title>
            <link>https://medium.com/@sandeantony?source=rss-8885f7052217------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:13:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandeantony/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[JavaScript to React 9— Create React App]]></title>
            <link>https://medium.com/@sandeantony/javascript-to-react-9-create-react-app-c3c58e9f8d3e?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3c58e9f8d3e</guid>
            <category><![CDATA[no-config]]></category>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Tue, 30 Apr 2019 17:54:55 GMT</pubDate>
            <atom:updated>2019-04-30T17:54:55.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /></figure><p><em>This is the ninth in a series of posts which cover the introductory concepts in React.</em></p><p>In the previous article, we learned how to set up our development environment using tools like Webpack and Babel. While these tools tremendously improve our developer experience, installing and configuring them can be frustrating for a beginner and time-consuming for experienced developers alike. While it is important to properly set up our development environment before creating our React applications, this can be a major distraction when learning to create React applications and it is also time-consuming if all we want to do is to quickly mock-up a simple React application for a prototype.</p><p>This is why the team at Facebook created a command-line tool called <a href="https://facebook.github.io/create-react-app/"><strong>Create React App</strong></a> (<strong>CRA</strong>) which is a <em>meta-package</em> that allows us to create new React applications that come with tools like Webpack and Babel already pre-configured and hidden from us in order to make it easier for us to create and start working on new React projects.</p><p><strong>NOTE</strong>: Even though CRA creates for us a pre-configured React project, it is still very important to <em>learn and understand how to configure</em> our applications. This will enable us to understand what goes on behind the scenes in our React applications and we shall be in a much better position to fix any configuration related bugs in our applications. We have already learned how to configure a simple React application using Webpack and Babel in a manner similar to how CRA works. However, just like <a href="https://medium.com/@dan_abramov">Dan Abramov</a> says in his talk “<a href="https://youtu.be/G39lKaONAlA?t=874">The Melting Pot of JavaScript</a>”, <em>Configuration should not stand in the way of getting started.</em></p><p>CRA allows us to set up a modern web application by running one command, thus it lets us focus on code, and not build tools like Webpack and Babel. It is, therefore, a great fit for learning React in a comfortable and feature-rich development environment.</p><p>To create a new React project called my-app using CRA, we run this command on the terminal:</p><pre>npx create-react-app my-app</pre><h4><a href="https://www.npmjs.com/package/npx">npx</a></h4><p>In the previous articles, we learned about <strong>npm</strong>. We learned that if a package that we are downloading from npm is going to be used as a command line tool, like create-react-app is, then we have to install it globally using the -g flag (npm install -g create-react-app). After this, the installed package can be used as create-react-app my-app.</p><p>However, since we shall typically use create-react-app once in a blue moon, by the time we run it again, it will already be far out of date, so we end up having to run an install/update it every time we want to use it. In order to help address this, npm v5.2 and above comes with a new binary alongside it called <a href="https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b"><strong>npx</strong></a>. npx allows us to execute create-react-app as a one-off command without installing it globally in our computer. Awesome!</p><p>Once the installation is done, we can switch to our project folder and start the app with the npm start command:</p><pre>cd my-app<br>npm start</pre><p>Then we open <a href="http://localhost:3000/">http://localhost:3000/</a> on the browser to see our app.</p><p>When we are ready to deploy to production, we create a minified bundle with npm run build.</p><h4>Folder Structure</h4><p>CRA creates an initial folder structure shown below:</p><pre>my-app<br>├── README.md <br>├── node_modules <br>├── package.json <br>├── .gitignore <br>├── public <br>│   ├── favicon.ico <br>│   ├── index.html <br>│   └── manifest.json <br>└── src <br>    ├── App.css <br>    ├── App.js <br>    ├── App.test.js <br>    ├── index.css <br>    ├── index.js <br>    ├── logo.svg <br>    └── serviceWorker.js</pre><p>We can delete and rename all the files apart from the public/index.html (the page template) and the src/index.js (the JavaScript entry point) which must exist with the exact filenames. We develop our React application by adding new JS and CSS files inside the src folder. We may also create subdirectories inside the src folder.</p><p>Note how similar this structure is to the folder structure we ended up with in our previous article. Apart from the few additional files (public/favicon.ico, public/manifest.json, src/App.test.js and src/serviceWorker.js), the main difference between these two folder structures is the fact that in the CRA folder structure, the webpack.config.js file is hidden from us and we only have the files we need to build our app.</p><p>So where is the Webpack configuration? If we take a look at the package.json file of our my-app project, we note a single dev dependency react-scripts. <a href="https://www.npmjs.com/package/react-scripts">react-scripts</a> is an npm package specifically for use with create-react-app and it is where the dependencies such as Webpack and Babel are specified and where the config files for Webpack and Babel are defined. It also contains additional configuration for an even more enhanced developer experience.</p><p>We can now go ahead and start building our React applications!</p><p>For more details on using Create React App, refer to the official <a href="https://facebook.github.io/create-react-app/docs/getting-started">documentation</a>.</p><p>This is part nine in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3c58e9f8d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript to React 8— Beyond JavaScript]]></title>
            <link>https://medium.com/@sandeantony/javascript-to-react-8-beyond-javascript-1996423eec6?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/1996423eec6</guid>
            <category><![CDATA[static-assets]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 17:18:18 GMT</pubDate>
            <atom:updated>2019-04-27T17:32:13.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /></figure><p><em>This is the eighth in a series of posts which cover the introductory concepts in React.</em></p><p>In this post, we shall look at how to work with CSS and images in our app. Since Webpack treats all kinds of files as modules, we are able to use it to build, pre-process and bundle our assets.</p><h3>Loading CSS</h3><p>Just like we did with our .js and .jsx files, we need to add Webpack loaders to help us handle our stylesheets. In order to import CSS files from within our JavaScript modules, we need to install and add the <a href="https://webpack.js.org/loaders/style-loader">style-loader</a> and <a href="https://webpack.js.org/loaders/css-loader">css-loader</a> to our Webpack config. We shall install them using the following command:</p><pre>npm install --save-dev style-loader@0.23.1 css-loader@2.1.1</pre><p>The command above installs two npm packages:</p><ol><li><a href="https://webpack.js.org/loaders/style-loader">style-loader</a> — this is a Webpack loader that adds CSS to the DOM by injecting a &lt;style&gt; tag into the &lt;head&gt; of our HTML file.</li><li><a href="https://webpack.js.org/loaders/css-loader">css-loader</a> — this is a Webpack loader that interprets CSS @import and url() statements like JavaScript’s import/require() and resolves them.</li></ol><p>Next, we shall add a new rule to our webpack.config.js file to use Webpack in processing our CSS files:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e1dbd8cda63ca0399866d9ee77f40dd/href">https://medium.com/media/9e1dbd8cda63ca0399866d9ee77f40dd/href</a></iframe><p>The test property tells Webpack to look for all files that end with a .css file extension. The use property tells Webpack to serve the CSS files to the style-loader and the css-loader.</p><p><strong>NOTE</strong>:</p><ul><li>that we passed an array to the use property containing two loaders instead of a single object like in our previous example. Passing multiple loaders is called <strong>chaining</strong>. Whenever we chain loaders, they are applied from right to left. Therefore in our example, the CSS file will be passed through the css-loader first, which will resolve the CSS imports and enable us to import them in JavaScript, and then through the style-loader, which will add the styles to our HTML file.</li><li>that passing a string to the use property (&quot;style-loader&quot;) is a short form that is equivalent to passing an object with the loader property ({ loader: &quot;style-loader&quot;).</li></ul><p>Adding these two loaders will thus enable us to use statements like import &quot;./style.css&quot; in our JavaScript files to load our stylesheets.</p><p>To see this in action, we shall add a CSS file to our app. Inside the src folder in our react-webpack-demo we shall create a new CSS file named index.css with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6dcdebef8178b8315e4a4cbae211154/href">https://medium.com/media/d6dcdebef8178b8315e4a4cbae211154/href</a></iframe><p>The CSS file contains rules to style the page by stripping the margin and padding from the body and setting a default font family. In order for Webpack to add our CSS file to the bundle, we will import it into our index.js JavaScript file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc607823b0e4acd48e1e9320a500c59/href">https://medium.com/media/4cc607823b0e4acd48e1e9320a500c59/href</a></iframe><p>If we run our app right now, we will see the styles change. They are however not so pronounced, so we shall add some more styles. We shall modify our App.jsx React component and add a new file in the src folder named App.css:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d470ca2243dc7d197d7cf00f128c6ac/href">https://medium.com/media/7d470ca2243dc7d197d7cf00f128c6ac/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f82885a1d9cc0e316e9439c03cc772d/href">https://medium.com/media/0f82885a1d9cc0e316e9439c03cc772d/href</a></iframe><p>We updated our App component to contain a header and a paragraph. We then added class names to each of the elements so that we can style them using CSS. We also imported our App.css file in the component.</p><p>App.css on the other hand, contains CSS to modify the App component. We align all the content to the center, give the header a dark background color, height, and padding, increase the font size of the title text and the font size of the paragraph text (we also have styles for app-logo which we shall use later in the article). This is how our app looks like right now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*0tmHqbvewXEq3-HY3k3JzA.png" /></figure><h3>Loading Images</h3><p>In order to load images from within our JavaScript modules, we need to install and add the <a href="https://webpack.js.org/loaders/file-loader/">file-loader</a> package to our Webpack config. We shall install it using the following command:</p><pre>npm install --save-dev file-loader@3.0.1</pre><p>Next, we shall add a new rule to our webpack.config.js file to use Webpack in processing our images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/356c9f9fc79b81803949d0ef2c8c7781/href">https://medium.com/media/356c9f9fc79b81803949d0ef2c8c7781/href</a></iframe><p>The test property tells Webpack to look for all files that end with a .png, .svg, .jpg or .gif file extension. The use property tells Webpack to serve the matched image files to the file-loader.</p><p>We added an SVG image named <a href="https://github.com/antosan/react-webpack-demo/blob/master/src/logo.svg">logo.svg</a> in the src folder. Now, when we import logo from “./logo.svg” inside the App.jsx file, that image will be processed and added to our output directory and the logo variable will contain the final URL of that image after processing. <strong>NOTE</strong> that we added the publicPath: “/build/” to the output key of our Webpack config on Line 8 for this to work. <a href="https://webpack.js.org/configuration/output/#outputpublicpath">output.publicPath</a> is an important option when loading external resources like images. It specifies the public URL of the output directory when referenced in a browser. It should start and end with / because it is prefixed to every URL created by the loader.</p><p>Inside App.jsx, we can use our image by including the logo variable in the src attribute of an image tag like this:</p><pre>&lt;img src={logo} className=&quot;app-logo&quot; alt=&quot;logo&quot; /&gt;</pre><p>In our App.css, we give the image with a class of .app-logo a height of 80px.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2d9c1a252a02a2171fe688a31eb7c52/href">https://medium.com/media/e2d9c1a252a02a2171fe688a31eb7c52/href</a></iframe><p>If all went well, we should now see the React logo appear on the page above the “Welcome to React” text. This is how our app looks like right now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*mOaXHqcYulFmzTptAmOqZw.png" /></figure><p>If we inspect this element, we see that the actual filename has changed to something like 5d5d9eefa31e5e13a6610d9fa7a283bb.svg. This means Webpack found our file in the src folder and processed it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*ZPTRAWHuLsr00lN8n0RPaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*aMFTTKLdQDbkE6fy-sbtvg.png" /></figure><p>The source code for the react-webpack-demo is available on <a href="https://github.com/antosan/react-webpack-demo">Github</a>.</p><p>This is part eight in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1996423eec6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript to React 7— Babel and Webpack]]></title>
            <link>https://medium.com/@sandeantony/javascript-to-react-7-babel-and-webpack-b6e8cdef509e?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6e8cdef509e</guid>
            <category><![CDATA[webpack4]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[babeljs]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 17:02:03 GMT</pubDate>
            <atom:updated>2019-04-27T17:31:47.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/95YRwf6CNw8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément H</a> on <a href="https://unsplash.com/@clemhlrdt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>This is the seventh in a series of posts which cover the introductory concepts in React.</em></p><p>In the last post, we looked at package management using npm. In this post, we shall cover how to compile and bundle our code using <a href="http://babeljs.io/">Babel</a> and <a href="https://webpack.js.org/">Webpack</a>.</p><h3>Babel</h3><p>We have seen how to use Babel to transform our JSX into JavaScript that the browsers can understand. We will also use Babel to transform our ES modules import syntax so that we can run it in the browser. Unlike before, however, we shall use the Babel npm package and not the CDN link.</p><p>We shall create a new empty folder for this example. We will call our folder react-webpack-demo. We shall initialize a new project in the react-webpack-demo folder by running npm init -y inside the folder. This will create for us the package.json file. The -y flag tells npm to use the default values for the fields in the package.json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*9_j8F0m5_aQ8ECyHKuYU8g.png" /></figure><p>We will create three new folders inside our react-webpack-demo folder. The first one will be named public, the second one named src and the third one named build. The public folder will contain our index.html file, which React will use to render our app. The src folder will contain our application written using JavaScript ES modules, JSX and any other JavaScript language features which are not currently supported in the browser. The build folder will, on the other hand, contain the JavaScript code that has been transpiled by Babel and that can be executed directly by the browser.</p><p>Our react-webpack-demo folder should now have the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*f6jgv24Jnd0uDpz-vAvzAw.png" /></figure><p>Inside the public folder, we will create a new file named index.html with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a39c9c1f3926b4c01490c97bb2c4e733/href">https://medium.com/media/a39c9c1f3926b4c01490c97bb2c4e733/href</a></iframe><p>The code in this file should be familiar. The div with the id of root is where we shall mount our React app. &lt;script src=”../build/bundle.js”&gt;&lt;/script&gt; loads a file called bundle.js. This file will be generated by Webpack (we shall cover this later on in the article).</p><p>Inside the src folder, we will create two new JavaScript files.</p><p>The first one will be named App.jsx (with an uppercase “A” — it is a common convention among React developers to name files that contain React components in PascalCase, with a .jsx extension). Add the following content to the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1a7f4c21331dd75718734c2a8fb5b76/href">https://medium.com/media/c1a7f4c21331dd75718734c2a8fb5b76/href</a></iframe><p>The second one will be named index.js with the following content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33d6fe274bff1ac5b5c67ad76c79ca3b/href">https://medium.com/media/33d6fe274bff1ac5b5c67ad76c79ca3b/href</a></iframe><p>We shall then install react and react-dom packages from npm by running the command below on the terminal from the root of our react-webpack-demo folder. This will also add both packages to our package.json file.</p><pre>npm install react@16.8.6 react-dom@16.8.6</pre><p>The App.jsx file contains a React component. The component renders a div with a p tag as its only child. In order to use this component elsewhere in our project, we need to export it so that it is accessible from other files. We export the component class using ES6 module syntax:</p><pre>export default App;</pre><p>This allows us to access the App component from the index.js file by importing it using ES6 module syntax:</p><pre>import App from &quot;./App.jsx&quot;;</pre><p>In the index.js file, we also import React, which is required since we are using JSX syntax (&lt;App /&gt;) and ReactDOM, which allows us to render our App component onto the div element with id=&quot;root&quot; (this div is in the index.html file in the public folder). We are able to use ES6 import/export statements in these files because they will be transpiled back to CommonJS module.exports and require statements using Babel.</p><h4>Setting up Babel</h4><p>The next step is to install Babel in our app. We shall install it from npm by running the command below on the terminal from the root of our react-webpack-demo folder. Since Babel will only be used during development, we shall pass the --save-dev flag while installing it:</p><pre>npm install --save-dev @babel/core@7.4.4 @babel/preset-env@7.4.4 @babel/preset-react@7.0.0</pre><p>Babel is split into multiple packages. In our case, we need to install three different Babel npm packages into our project and save them as devDependencies in our package.json file.</p><p>The three packages are:</p><ol><li><a href="https://babeljs.io/docs/en/next/babel-core.html">@babel/core</a> — this is the main Babel package that will be used to transform our code.</li><li><a href="https://babeljs.io/docs/en/next/babel-preset-env.html">@babel/preset-env</a> — in order to perform a transformation using Babel, we need to install a <strong>Babel plugin</strong> that enables that transform. Multiple plugins are required in a single React project. We don’t want to install each of these manually, which is why Babel provides presets. In Babel, <strong>a <em>preset</em> is a set of <em>plugins</em> used to support particular language features</strong>. The env Babel preset automatically determines the Babel plugins we need in our project based on our supported environments. By default, @babel/preset-env installs all the plugins needed to support all the new language features introduced in ES2015 and later.</li><li><a href="https://babeljs.io/docs/en/next/babel-preset-react.html">@babel/preset-react</a> — this Babel preset contains Babel plugins that transform JSX into React.createElement calls.</li></ol><p>But even after installing a preset, we need to tell Babel to use it. The recommended way to do this is to create a new file at the root of our react-webpack-demo folder named .babelrc (<strong>NOTE</strong>: the filename begins with a dot). We use this file to enable Babel plugins/presets. Add the following to the .babelrc file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5990d7e1b365960f7febec43dbafab6/href">https://medium.com/media/e5990d7e1b365960f7febec43dbafab6/href</a></iframe><h3>Webpack</h3><p>Webpack is an open-source JavaScript module bundler. Webpack takes modules with dependencies and generates static assets representing those modules. It takes the dependencies and generates a dependency graph allowing web developers to use a modular approach for their web application development purposes. The bundler can be used from the command line or can be configured using a config file.</p><p>Webpack is a tool that analyzes our project’s structure, finds JavaScript modules and other assets to bundle and packs them for the browser. It analyzes our project as a whole. Given a starting main file, Webpack looks through all of our project’s dependencies (by following import statements in JavaScript), processes them using loaders and generates a bundled JavaScript file.</p><p>We shall add Webpack to our app by installing it from npm by running the command below on the terminal from the root of our react-webpack-demo folder. Since Webpack will only be used during development, we shall pass the --save-dev flag while installing it:</p><pre>npm install --save-dev webpack@4.30.0 webpack-cli@3.3.1 webpack-dev-server@3.3.1 babel-loader@8.0.5</pre><p>The command above installs four npm packages:</p><ol><li><a href="https://github.com/webpack/webpack">webpack</a> — this is the main Webpack package that will be used to bundle our code.</li><li><a href="https://webpack.js.org/api/cli/">webpack-cli</a> — this is Webpack’s command line interface that allows us to bundle our modules from the command line.</li><li><a href="https://github.com/webpack/webpack-dev-server">webpack-dev-server</a> — this is Webpack’s optional server for local development purposes. It eliminates the need to manually trigger a rebuild of our source code after every little change, which is a slow and annoying process. It is a small Node.js server, made using a library called <a href="http://expressjs.com/">Express</a>, that serves static files and builds our assets according to our Webpack configuration, keeping them in memory, and automatically refreshing the browser as we change our source files.</li><li><a href="https://github.com/babel/babel-loader">babel-loader</a> — this is a Webpack plugin for Babel. This package allows JavaScript files to be transpiled using Babel and Webpack.</li></ol><p>Webpack can be a complex tool to use. It, therefore, provides incredible configuration options to fit any project that uses it. From the <a href="https://webpack.js.org/concepts/">Webpack documentation</a>, it is important to understand Webpack’s four core concepts before creating the configuration for our project.</p><p>Webpack’s core concepts from the documentation are:</p><ol><li><a href="https://webpack.js.org/concepts/#entry"><strong>Entry </strong></a>— An entry point indicates which module Webpack should use to begin building out its internal <em>dependency graph.</em> Webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly). It defaults to ./src/index.js.</li><li><a href="https://webpack.js.org/concepts/#output"><strong>Output </strong></a>— The output property tells Webpack where to emit the <em>bundles</em> it creates and how to name these files, it defaults to ./dist/main.js for the main output file and to the ./dist folder for any other generated files.</li><li><a href="https://webpack.js.org/concepts/#loaders"><strong>Loaders</strong></a> — Out of the box, Webpack only understands JavaScript files. Loaders allow Webpack to process other types of files by converting them into valid <a href="https://webpack.js.org/concepts/modules">modules</a> that can be consumed by our application and added to the dependency graph. At a high level, loaders have two purposes in our Webpack configuration: the test property, which identifies which file or files should be transformed, and the use property, which indicates which loader should be used to do the transformation.</li><li><a href="https://webpack.js.org/concepts/#plugins"><strong>Plugins</strong></a> — Plugins are used to perform a wider range of tasks like bundle optimization, assets management and injection of environment variables. In order to use a plugin, we need to require() it and add it to the plugins array. Most plugins are customizable through options. Since we can use a plugin multiple times in the config file for different purposes, we need to create an instance of it by calling it with the new operator.</li></ol><p>We shall now go ahead and create a Webpack configuration for our project. By default, Webpack will look for a file named webpack.config.js in the root folder of our project. We will, therefore, create a new webpack.config.js file at the root of our react-webpack-demo folder, and add a few basic configuration options.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf6054c6040d2883e9b19d77fdfae49e/href">https://medium.com/media/cf6054c6040d2883e9b19d77fdfae49e/href</a></iframe><p>In our webpack.config.js configuration file, we get to use the require statement that we introduced when talking about using npm packages in our project. Node.js uses the <strong>CommonJS</strong> module system. The require statement is used to load modules in Node.js. The main difference here is that the path module that we are loading was not installed from npm. Node.js has several modules compiled into its binary. These are referred to as <strong>Core Modules</strong>. Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require(&quot;path&quot;) will always return the built-in path module, even if there is a file by that name.</p><p>The <a href="https://nodejs.org/api/path.html">path</a> module provides utilities for working with file and directory paths. It can be accessed using:</p><pre>const path = require(&quot;path&quot;);</pre><p>The path.resolve() method resolves a sequence of paths or path segments into an absolute path. Using path.resolve(__dirname, &quot;dist&quot;) appends the path name dist to the current value of the __dirname variable. __dirname returns the directory name of the current module. For example, if we run console.log(path.resolve(__dirname, &quot;dist&quot;)) from a file in the /Users/antosan directory, then the absolute path that will be printed out will be /Users/antosan/dist.</p><p><strong><em>NOTE</em></strong><em>: We</em> <em>use Node’s built-in </em><a href="https://nodejs.org/api/path.html"><em>path module</em></a><em> and prefix it with the </em><a href="https://nodejs.org/docs/latest/api/globals.html#globals_dirname"><em>__dirname</em></a><em> variable to prevent file path issues between operating systems (Mac, Linux, Windows) and also to allow relative paths to work as expected.</em></p><p>The <strong>module.exports</strong> is a special object which is included in every JavaScript file in Node.js applications by default. module is a variable that represents the current module and exports is an object that will be exposed as a module. So, whatever we assign to module.exports, will be exposed as a module. The module.exports object in every module is what the require function returns when we require that module. Our Webpack config will be assigned to module.exports so that our application can use it.</p><p>Webpack requires us to provide a single entry file from which it will figure out the dependencies of the project automatically. We provide this file using the entry key in the configuration object that we export. We set our index.js file to be the entry file (which is the same file that is used by default if none is provided).</p><pre>entry: &quot;./src/index.js&quot;</pre><p>Webpack also requires that we provide a file and folder where it shall save the files that it bundles. These are provided through the output key in the configuration object that we export. We instruct Webpack to use ./build/bundle.js as the main output file and use the ./build folder for any other generated files.</p><pre>output: {</pre><pre>    path: path.resolve(__dirname, &quot;build&quot;),</pre><pre>    filename: &quot;bundle.js&quot;</pre><pre>}</pre><p>Since our project uses ES6 syntax, we need to instruct Webpack to use Babel to transpile this code back to ES5 syntax. We do this using <strong>Webpack Loaders</strong>. Loaders are provided through the module key in the configuration object that we export. module.rules is an array of <a href="https://webpack.js.org/configuration/module/#modulerules">Rules</a> which are matched to requests when modules are created. These rules can modify how the module is created and this is how we apply loaders to the module. At a high level, loaders have two purposes in our Webpack configuration: the test property, which identifies which file or files should be transformed — in our case all files with a .js or .jsx file extension (we specify this using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp">RegExp</a> /\.(js|jsx)$/), and the use property, which indicates which loaders should be used to perform the transformation — in our case, we would like to use the babel-loader that we installed from npm. We also specify exclude: /node_modules/ to instruct Webpack to ignore the files in the node_modules folder when using Babel to transpile the code.</p><pre>module: {</pre><pre>    rules: [</pre><pre>        {</pre><pre>            test: /\.(js|jsx)$/,</pre><pre>            exclude: /node_modules/,</pre><pre>            use: {</pre><pre>                loader: &quot;babel-loader&quot;</pre><pre>            }</pre><pre>        }</pre><pre>    ]</pre><pre>}</pre><h3>Running our first build</h3><p>Now that our webpack.config.js file is ready, we can go ahead and run our first build by executing Webpack from the terminal. Since we have installed Webpack locally in our project, as opposed to globally, we need to reference the Webpack command in the node_modules folder of our project. To build our project, we shall run the following command at the root of our react-webpack-demo folder.</p><pre>node_modules/.bin/webpack --mode development</pre><p><strong>NOTE</strong>: We pass a --mode flag to the command and set its value to development. We can set mode to either development or production. Webpack uses the mode configuration option to determine which of its built-in optimizations it should apply to our build whether we are in the development or production environment. In the development environment, we desire to have a good developer experience by having useful error messages, fast incremental compilation, a localhost server with live reloading e.t.c. In the production environment, we desire that our build is optimized for deployment i.e. minified bundles, omitting development-only code and optimized assets to improve load time. It is typically recommended to write separate Webpack configuration for each environment, but for our small example, it is okay to re-use the same configuration and let Webpack apply for us the default development and production optimizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*_2OEWEJP_vFSDqlBLbTPlA.png" /></figure><p>Notice that Webpack bundled both the App.jsx and the index.js files and created a new file in our build folder named bundle.js. If we open the index.html file in the browser, the result will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*SiMHyJN2p4fpqaq19Q-TIA.png" /></figure><h3>Adding Task Shortcuts</h3><p>We can avoid using the long node_modules/.bin/webpack command and instead run it from the package.json&#39;s scripts object as an npm task (npm is also a task runner). To achieve this, we shall start by deleting the test script from the package.json file:</p><pre>&quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</pre><p>Then we shall add a start script that runs our command for us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*nzMvkGUfXmI09ZAVMWuVlw.png" /></figure><p>We also added a build script that will execute the same command but with production optimizations.</p><p><strong>NOTE</strong>: The scripts configured in the package.json file already have the node_modules/.bin folder in the path, so we do not need to explicitly call the desired command with the full path.</p><p>In order to run the commands we have defined, we use the <a href="https://docs.npmjs.com/cli/run-script">npm run-script</a> command. We will use the alias npm run &lt;command&gt;.</p><p>npm run start will run the development build. We can also use the shorter npm start command to run the start script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*7jV-YfNOVow3ygC0THKSYQ.png" /></figure><p>npm run build will run the production build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*bKoFRVL-jac7tKidf_lNpg.png" /></figure><p><strong>NOTE</strong>: The size of the generated bundle.js file is much smaller in the production build (119 KB) as compared to the development build (910 KB).</p><h3>Webpack Dev Server</h3><p>Whenever we change our source files, we have to manually run the npm start script to bundle the code and then refresh the browser ourselves. This is a slow and annoying process which leads to poor developer experience. <em>Developer Experience (DX)</em> is all about how developers feel while writing software. There are a number of tools which exist to help improve the developer experience of React developers.</p><p><a href="https://github.com/webpack/webpack-dev-server">Webpack Dev Server</a> is Webpack’s optional server for local development purposes. It eliminates the need to manually trigger a rebuild of our source code after every little change, which is a slow and annoying process. It is a small Node.js server, made using a library called <a href="http://expressjs.com/">Express</a>, that serves static files and builds our assets according to our Webpack configuration, keeping them in memory, and automatically refreshing the browser as we change our source files. This is referred to as <strong>Live Reloading</strong> (i.e. full app-wide reload).</p><p>Since we already installed webpack-dev-server, we shall configure it in our webpack.config.js file by adding a devServer key to the exported object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SrpoOsoINIa8c-G30Vjopw.png" /></figure><p><a href="https://webpack.js.org/configuration/dev-server/#devserver">webpack-dev-server</a> provides several options that are used to affect its behavior. The options we use in our example are:</p><ul><li><a href="https://webpack.js.org/configuration/dev-server/#devservercontentbase">contentBase</a>: tells the server where to serve our static files from. In our case, this is the public folder, which contains our index.html file.</li><li><a href="https://webpack.js.org/configuration/dev-server/#devserverport">port</a>: specifies the port number to listen to requests on.</li><li><a href="https://webpack.js.org/configuration/dev-server/#devserverpublicpath-">publicPath</a>: tells the server the location of our bundled files in the browser. For example, if our server is running at http://localhost:3000 and output.filename is set to bundle.js our bundle will be available at <a href="http://localhost:3000/bundle.js">http://localhost:3000/bundle.js</a> (publicPath is &quot;/&quot; by default). Since our bundle is in a directory named build, we shall set our publicPath to /build/ (<em>make sure </em><em>publicPath always starts and ends with a forward slash</em>). We can access our bundle in the browser at this link: <a href="http://localhost:3000/build/bundle.js">http://localhost:3000/build/bundle.js</a>.</li><li><a href="https://webpack.js.org/configuration/dev-server/#devserveropen">open</a>: instructs the dev server to open the default browser.</li><li><a href="https://webpack.js.org/configuration/dev-server/#devserveroverlay">overlay</a>: when enabled, the dev server shows a full-screen overlay in the browser when there are compiler errors or warnings.</li></ul><pre>devServer: {<br>    contentBase: path.resolve(__dirname, &quot;public&quot;),<br>    port: 3000,<br>    publicPath: &quot;/build/&quot;,<br>    open: true,<br>    overlay: true<br>}</pre><p>We will then adjust our npm script in the package.json file to use webpack-dev-server to run our development build instead of using webpack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*OuNOnoBrt4UrDdOEOIThnA.png" /></figure><p>Now, if we start our server by running npm start, the dev server will bundle our code and automatically open our app in the default browser. Whenever we make any changes to our source files, the dev server will re-build our app and refresh the browser automatically.</p><p>The source code for the react-webpack-demo is available on <a href="https://github.com/antosan/react-webpack-demo">Github</a>.</p><p>This is part seven in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6e8cdef509e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript to React 6 — Development Environment]]></title>
            <link>https://medium.com/@sandeantony/javascript-to-react-6-development-environment-73cc8a61b257?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/73cc8a61b257</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 15:52:01 GMT</pubDate>
            <atom:updated>2019-04-28T04:42:02.825Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript to React 6 — Development Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/95YRwf6CNw8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément H</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>This is the sixth in a series of posts which cover the introductory concepts in React.</em></p><p>So far, we have introduced the most basic React concepts using a very lightweight solution. All our code was written in a single HTML file. While this setup was perfect for introducing React concepts, it does not offer a great developer experience.</p><p>In order to start building React applications, we need to set up our development environment so that we can use the latest JavaScript features, have a nice developer experience, and optimize our app for production. Such a development environment typically consists of:</p><ul><li>A <strong>package manager</strong>, such as <a href="https://www.npmjs.com/">npm</a>.</li><li>A <strong>compiler</strong>, such as <a href="http://babeljs.io/">Babel</a>.</li><li>A <strong>bundler</strong>, such as <a href="https://webpack.js.org/">Webpack</a>.</li></ul><h3>Package management in JavaScript</h3><p>Up until this point, we have manually loaded all our scripts via the &lt;script&gt; tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFeIS3XPfvQwOphDzVOQzQ.png" /></figure><p>Each of these script tags links to a third party library hosted on a CDN. It is however not easy to manage these libraries when they are loaded using scripts. For example, since ReactDOM depends on React to be available for it to work properly, we must make sure that we load them in the correct order to avoid running into errors. It is also difficult to upgrade/downgrade to different versions of these libraries, especially when working in a team. Previously, as a workaround, in order to maintain specific versions of different libraries, most developers downloaded the library’s code into a vendor folder in their local environment and linked to these local versions in the script tags. However, package managers are here to help solve this problem.</p><p>According to <a href="https://en.wikipedia.org/wiki/Package_manager">Wikipedia</a>, A <strong>package manager</strong> or <strong>package management system</strong> is a collection of software tools that automate the process of installing, upgrading, configuring, and removing computer programs for a computer’s operating system in a consistent manner.</p><p>A <em>package</em> is a reusable piece of software which may or may not depend on other packages and can be downloaded from a global registry into a developer’s local environment. Packages are sometimes referred to as modules. The most popular package manager used in JavaScript is called <a href="https://www.npmjs.com/"><strong>npm</strong></a>.</p><h4>Installing npm</h4><p>npm is distributed with <a href="https://nodejs.org/">Node.js</a>, which means that when we download Node.js, we automatically get npm installed on our computer. <strong>Node.js</strong> is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code on the server. To put it simply, <strong>Node.js lets us run JavaScript from the command line</strong>.</p><p>In order to install Node.js, we need to download the LTS (Long Term Support) version of the software for our operating system from <a href="https://nodejs.org">https://nodejs.org</a>. As at the time of writing this article, it is version <strong><em>10.15.3</em></strong>.</p><p>After installation, we shall use the command line/terminal to interact with the npm command line tool. We can confirm that we have installed Node.js by running the following command on the terminal:</p><pre>node -v</pre><p>We should see a version number returned, e.g. v10.15.3.</p><p>To confirm that we have installed npm, we run the following command on the terminal:</p><pre>npm -v</pre><p>We should see a version number returned, e.g. 6.9.0.</p><p>Great! npm is now working on our local environment.</p><h4>Package management using npm</h4><p>Packages contain <em>metadata</em> (data that contains information about other data), such as the package’s name, description of its purpose, version number, author, and a list of dependencies necessary for the package to run properly. When working with npm, this metadata is stored in a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> (JavaScript Object Notation) file at the root of our project. This file is named <strong>package.json</strong>.</p><p>In order to learn about how to use npm, we shall create a new folder named npm-example and open it up in our terminal.</p><p>Whenever we start a new project we need to run the following command from our project folder to initialize and begin using npm (we shall run this at the root of our npm-example folder):</p><pre>npm init</pre><p>The npm init command is responsible for creating the package.json file. It asks a series of questions whose answers will be the contents of the package.json file. We type the response to each question at the question prompt (or leave it blank) and press enter to proceed to the next question. After answering the last question, a preview of the package.json file will be displayed and we are required to confirm that we would like to create it by typing <strong>yes</strong> or <strong>y</strong> and pressing enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*taQUKZN3Q_tXsErmmDeZxQ.png" /></figure><p>After successfully running npm init, the package.json file will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IInOjG5Z3hHuQOGwuRgIPA.png" /></figure><h4>Installing npm packages</h4><p>We use the npm install command to install npm packages. We can find packages to help us build our applications by browsing the <a href="https://www.npmjs.com/">npm</a> website. On the website, we will find different kinds of packages: there are lots of packages which we can use on the server or on the browser in our applications, and there are packages which are commands for us to use on the command line.</p><p>Packages that we shall use in our project and in the development of our project are referred to as <strong>local packages</strong> and are installed locally. Packages that we use as command line tools are referred to as <strong>global packages</strong> and are installed globally.</p><h4>Installing local npm packages</h4><p>Our project currently uses React as a script from the CDN. If instead, we wanted to install the React package from npm, we need to run the following command on the terminal at the root of our project folder:</p><pre>npm install react</pre><p>The npm install command has a short way of writing it (an alias). The same command above looks like this as an alias:</p><pre>npm i react</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*44VULgvuM4PtfLvfqGgOeg.png" /></figure><p>npm install &lt;package&gt; saves any specified packages (in our case, the react package) into dependencies by default. However, in older versions of npm, we had to explicitly instruct npm to save the package to the package.json file by passing the --save flag i.e. npm install --save react or the alias npm i -S react. Note that the alias flag is an uppercase “S”. This is the default however in newer versions of npm.</p><p>If we look at our package.json file after running this command, we will notice that a new dependencies object has been added to the JSON and it lists react as one of its keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*kYszedBz-swTBfw-lY7wew.png" /></figure><p>npm downloads packages from the npm registry. By default, npm installs the latest version of the package that has been published on the npm registry. The version that was installed will be listed in the package.json file.</p><p>In the snippet above, the version of react that was installed is version 16.8.6. npm uses a versioning standard called <a href="https://docs.npmjs.com/getting-started/semantic-versioning">Semantic Versioning (semver)</a>. Semantic Versioning lists package versions using three digits: the first digit (16) represents the <strong>major release</strong> of the package, the second digit (8) represents the <strong>minor release</strong> under this major release, and the third digit (6) represents the <strong>patch/bug fixes</strong> released under this minor release.</p><p>The version number in the package.json has a carat (aka hat) symbol ^ before it. The ^ tells npm to <em>include everything greater than a particular version in the same major range</em>. In our case, if the react package in the npm registry is updated to version 16.8.7 (patch release) or version 16.9.0 (minor release) and we run npm update in our project, the new version will be installed. However, if the react package in the npm registry is updated to version 17.0.0 (major release) and we run npm update, the new version will not be installed — major releases normally have breaking changes i.e. changes that are most likely to change how the package works and therefore introduce errors that break our application, and it is not advised to install major updates automatically.</p><p>If we look at our project folder, we notice that there is a new file created named package-lock.json. This file is automatically generated when we run any operations where npm modifies the package.json file. This file describes the exact dependency tree that should be used whenever we install the packages listed in the package.json file. This lock file is intended to pin down (lock) all versions for the entire dependency tree at the time that the lock file is created and thus ensure that npm does not automatically install the latest version of a package but rather the version that was originally intended for the specific package.</p><p>As an example, the react package that we installed also depends on other packages. All these packages will be listed as dependencies in the package-lock.json file. Below is a screenshot from the package-lock.json file that shows one of the packages known as prop-types that react depends on. Here, we see the metadata stored about the dependency: the <strong><em>version</em></strong> of the package that should be installed, the <strong><em>resolved</em></strong> registry location indicating from where this package was retrieved and from where it should be retrieved for future installs, an <strong><em>integrity</em></strong> hash used to provide assurance that the package hasn’t been tampered with, and all the other dependencies that this package <strong><em>requires</em></strong>, together with their versions. Each of these dependencies will have a similar entry in the package-lock.json file, and so on until all the dependencies are represented in the dependency tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zenU010Bv_VEYp6tFBYHCA.png" /></figure><p>When we run npm install &lt;package&gt; for the first time, npm creates a folder at the root of our project named node_modules and it downloads the packages we have installed to this folder. If we share our code with other developers, e.g. using a versioning system such as <a href="https://git-scm.com/">Git</a> and <a href="https://github.com/">Github</a>, then we do not share this node_modules folder. As long as our project has a package.json file with dependencies listed in it, running npm install (without specifying any package) will recreate the node_modules folder and download all the packages into it.</p><p>We can pass multiple packages at once (separated with space) in order to install them together:</p><pre>npm install react react-dom</pre><p>This will install both the react and react-dom npm packages and add both of them to the package.json file.</p><h4>Development Dependencies</h4><p>We used Babel in our beginner examples to transpile the JSX we wrote into JavaScript code that the browsers can understand. However, Babel is only required during the development of our web app and is not used anymore once our app has been deployed to production. When working with npm, packages such as Babel are known as <strong>development dependencies</strong>.</p><p>Development dependencies are packages that we need during the creation of our app, but which are not required in production. Examples include unit testing tools, code linters or transpilers like Babel, which produce our production code at build-time and are not needed in production. Production dependencies are those dependencies that are required for our app to run in production, like React itself.</p><p>In order to install a package as a development dependency, we run the npm install &lt;package&gt; command and pass it the --save-dev flag:</p><pre>npm install --save-dev &lt;package&gt;</pre><p>Or we can use the alias:</p><pre>npm i -D &lt;package&gt;</pre><p>Note that the alias flag is an uppercase “D”.</p><p>This will install the Babel package in our project:</p><pre>npm install --save-dev @babel/cli</pre><p>If we look at our package.json file after running this command, we will notice that a new devDependencies object has been added to the JSON and it lists @babel/cli as one of its keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*mJGPVHbPTNYsJ-g_MHNAsQ.png" /></figure><p><em>We shall talk about Babel in more details in the next article…</em></p><p>Here is the complete package.json file for our example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZQAi3m6QD6o0pShNj-HEQ.png" /></figure><h4>Installing specific package versions</h4><p>It is possible that by the time you are reading this article, the latest package versions of react, react-dom and @babel/cli on the npm registry will be different from the ones shown above. While it is always advisable to use the latest package versions when starting out new projects, it is also advisable to use the packages used in this article when learning as future versions of these packages are not guaranteed to continue working in the same manner. So the question is how do we install a specific version of a package from npm?</p><p>To manually specify the exact package to install from npm, we append the version number of the package after the package name, separated by an “@” sign, as shown:</p><pre>npm i react@16.8.6 react-dom@16.8.6</pre><pre>npm i -D @babel/cli@7.4.4</pre><h4>Installing global npm packages</h4><p>If the package that we are downloading from npm is going to be used as a command line tool, then we have to install it globally. This ensures that we can be able to execute the command provided by the package no matter which directory is current.</p><p>In order to install a package globally, we run the npm install command and pass it the --global flag:</p><pre>npm install --global &lt;package&gt;</pre><p>Or we can use the alias:</p><pre>npm i -g &lt;package&gt;</pre><p>For example, we can run this to update npm to the latest version:</p><pre>npm install -g npm@latest </pre><p><strong>NOTE</strong>: It is difficult to know which packages from npm to use in our projects. The npm registry hosts a huge number of libraries that we can use in our projects, but since anyone with an account on npm is allowed to publish packages to the registry, we have to be careful when choosing which packages to include in our projects. When it comes to the choice of a package to use, the first option is to do a random search on the npm website for a package that matches the task we would like to accomplish, while the other option is to always ask a friend/google. The most popular packages on npm become second knowledge with time after reuse. After locating a package on the npm website, we should use the information on the npm website like number of downloads, number of depending packages, number of open issues and date last published to assess the quality and reliability of the package.</p><p>That was a brief introduction on how to use npm for package management in JavaScript. Now the next task is to understand how to use the packages installed in our node_modules folder.</p><h4>Using npm packages in our project</h4><p>JavaScript has several module systems which we can use to load the npm packages into our project. The module system used by most packages on npm is the <strong><em>CommonJS</em></strong> module system. The main concept in CommonJS modules is a function by the name require. When we call require with the module name of our dependency, it makes sure the module is loaded and available for use.</p><p>We will require the react and react-dom packages that we installed in order to use them in our project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_4ZfwXIJ6E5hDfZVnfQ2A.png" /></figure><p>Now the react package/module will be available to us through the React variable, while react-dom will be available through the ReactDOM variable. We will thus no longer need to load these packages in our head tag using their CDN links.</p><p>The CommonJS specification describes module APIs for JavaScript outside the browser. CommonJS became popular with the advancement of Node.js. With the advancement of ES2015, there is a native module system for JavaScript. These are referred to as <strong><em>ECMAScript</em></strong> Modules (or ES Modules). ES modules introduce a special import keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJfUiZsqHti10u2gf_2qQA.png" /></figure><p>Since ES modules have not been fully implemented by the browsers at the time of writing this article, we have to compile them in order for them to work in the browser. We shall explore how to do this in the next article.</p><p>This is part six in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73cc8a61b257" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript to React 5 — Working with Remote Data]]></title>
            <link>https://medium.com/@sandeantony/javascript-to-react-5-working-with-remote-data-122c467ace0d?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/122c467ace0d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-fetching]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Tue, 26 Mar 2019 17:07:26 GMT</pubDate>
            <atom:updated>2019-04-27T17:30:48.090Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript to React 5 — Working with Remote Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/95YRwf6CNw8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément H</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>This is the fifth in a series of posts which cover the introductory concepts in React.</em></p><p>Most real-world production React apps work with remote data. This data is usually fetched from a remote HTTP API (Application Programming Interface). It is therefore critical to understand how to work with remote data in React.</p><p>In order to make HTTP requests to an external server, we need to use an HTTP library. While there are several HTTP libraries available that work well with React, we shall use the <a href="https://github.com/mzabriskie/axios"><strong>axios</strong></a> HTTP library. axios is a Promise based HTTP client that works well in the browser.</p><p>Since axios uses Promises, it is important to understand how JavaScript Promises work.</p><h3>JavaScript Promises</h3><p>JavaScript is a single-threaded language, meaning that two bits of script cannot run at the same time; they have to run one after another. This means that for the most part, your JavaScript code is executed from top to bottom, line by line. When JavaScript gets to a particular line of code in our program, it will execute the code on that line first, before moving on to the following line — even if this code takes a long time to complete execution.</p><p>This is what is referred to as <strong>Synchronous</strong> code, and it is how JavaScript executes code most of the time. It basically waits (blocks) until one task is finished before it moves on to execute the next task.</p><p>When fetching data from a remote API, several factors will determine how fast we shall get a response from the server. We are usually not in control of most of these factors e.g. the internet connection speed or the amount and type of data being fetched from the server. If a call to the server is performed synchronously, then no other code will be executed as we are waiting for the response and we may end up with an accidental white screen on our app. This is not a good user experience for our app as it could be perceived by the user as latency or performance lag.</p><p>The solution to this problem is to write <strong>Asynchronous</strong> code. Asynchronous code allows a long-running task to be executed in the background without blocking the main thread. This means that the program will continue executing the following tasks without immediately waiting for the long-running process to complete execution. Asynchronous code, however, provides for a way for the process running in the background to notify the main thread when it is done with the execution and provides a way for the main thread to access its resulting value.</p><p>While there are several ways of writing asynchronous code in JavaScript, we shall only focus on one of them in this article: <strong>Promises</strong>.</p><p>As defined by Mozilla, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><strong>Promise</strong></a> object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. The Promise object is simply a wrapper around a value that may or may not be known when the object is created and provides a method for handling the value at a later time in the future when it is known (referred to as resolved) or when it is unavailable for a failure reason (referred to as rejected).</p><p>Promises have three possible mutually exclusive states (i.e. they cannot both occur at the same time):-</p><ul><li><strong><em>pending</em></strong>: initial state, neither fulfilled nor rejected.</li><li><strong><em>fulfilled</em></strong>: meaning that the operation completed successfully.</li><li><strong><em>rejected</em></strong>: meaning that the operation failed.</li></ul><p>When a new Promise is created, it is in the <strong><em>pending</em></strong> state and the long-running task begins being executed. If the long-running task executes successfully, the Promise is said to be resolved and enters the <strong><em>fulfilled</em></strong> state. The Promise provides a then() method, which allows us to set a handler function which will be called when the Promise resolves. We will have access to the resulting value in the then() method.</p><p>However, if the long-running task fails to execute for whatever reason, the Promise is said to be rejected and enters the <strong><em>rejected</em></strong> state. The Promise provides a catch() method, which allows us to set a handler function which will be called when the Promise is rejected. We will have access to the error in the catch() method so as to appropriately handle it.</p><p>The then() and catch() methods both return Promises as well, thus allowing us to chain them together.</p><h4>Creating a Promise</h4><p>While we do not need to understand how to create a Promise for our React data fetching example, we shall look at a basic example of creating a Promise and how to consume it.</p><p>A Promise object is created using the new keyword and its constructor. This constructor takes as its argument a function, called the “<em>executor function</em>”. The executor function takes two other functions as arguments. The first of these functions (resolve) is called when the asynchronous task completes successfully and returns the results of the long-running task as a value. The second function (reject) is called when the long-running task fails and returns the reason for failure, which is typically an error object. To provide a function with promise functionality, we simply make the function return a Promise:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6B4KzGaXYB3sk-Xi3TIIw.png" /></figure><p>In the snippet above, we create a function called getCurrentTime that returns a Promise. In the Promise’s executor function, we use JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">setTimeout</a> method to simulate asynchronous code by executing the code once after a delay of 2000 ms. We then use Math.random() to randomly cause the Promise to either call resolve with the current date, or call reject with an error.</p><h4>Consuming a Promise</h4><p>In order to use a function that returns a Promise, like our getCurrentTime() above, we call the then() method on the return value of the function. We pass in a function which will receive the resulting value that was resolved as an argument.</p><p>To handle any errors, we use the catch() method which receives the error that was passed to the reject call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2MJ1w1om58wBX3n7LSTSQ.png" /></figure><p>With that basic understanding of how JavaScript promises work, let us now get back to data fetching in React.</p><h3>Fetching data from an HTTP API</h3><p>In order to learn about fetching data from a remote API, we will build a simple app which will allow us to query information about different countries from a remote API. We shall use the <a href="http://restcountries.eu/#api-endpoints-name">REST Countries API v2</a> since it is free and does not require us to create an account to access the API.</p><p>The final app will work like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*ZtbJcV_kYMSxv3gFAN3Ofw.gif" /></figure><p>In a new file named datafetching.html we will create a new class component called App that renders a form with a single input of type=&quot;text&quot; and a button to submit the form. When this form is submitted, we shall log to the console the value which the user typed in the input. This value is stored in this.state.country. The component also manages three other items in its state, data, error and loading, which we shall use shortly. We should be familiar with the code up to this point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTf3B6Qakd7y8Z4H8Or5_g.png" /></figure><p>const { country } = this.state; uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring"><strong><em>ES6 Object destructuring</em></strong></a> to unpack the country value from the this.state object into a distinct variable called country.</p><p>Instead of logging out the value of the country to the console, we would like to fetch details about this country from the API using axios and display them in our app.</p><p>First, we include the axios script in the head tag using the CDN link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8wbA32o3RlWN0yXy-JYZDA.png" /></figure><pre>https://unpkg.com/axios/dist/axios.min.js</pre><p>When the form is submitted, the handleSubmit method is called. Inside this method, we can access the country value from this.state.country. We use the axios.get function to fetch the data from the REST Countries API, based on the this.state.country value. The back-ticks are an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals"><strong><em>ES6 template string</em></strong></a>. The ${this.state.country} part is replaced by the value of that expression, e.g. if the value in this.state.country is “kenya”, then the URL passed to axios.get will be <a href="https://restcountries.eu/rest/v2/name/kenya">https://restcountries.eu/rest/v2/name/kenya</a> (please visit this link on your browser to see the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> response that is sent back from the API).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QilAdFvELJX5fPbNFtEzGQ.png" /></figure><p>Since axios uses Promises, we chain the call with .then() to handle the response. axios.get will resolve after some time. We, therefore, pass a function into the then() method which will be called when the Promise resolves. This function will receive as an argument the response from the API. Inside the function, we will update three items in the component state: we set the country to an empty string to clear the country input field, we set the data to the data that we get back from the response (this is accessed from response.data), and we set the error to false, since we had no error.</p><p>If the country name provided is not supported by the API (or if there is any other error), the call to axios.get will reject after some time. We, therefore, chain it with .catch() to handle the error. We pass a function into the catch() method which will be called if the Promise rejects. This function will receive as an argument the error from the API. Inside the function, we will update two items in the component state: we set the data to an empty array and we set the error to true.</p><p>When the Promise resolves or rejects, we update the component state. This will result in the render method being called again to update the UI to match the current values in the state. Let us update our render method in order to display the results from the API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBE3wG-yjdua11E4knWRbg.png" /></figure><p>In the snippet above, we first <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring">destructure</a> data and error from the this.state object. Below the form, we embed a JavaScript expression inside our JSX by wrapping it in curly braces. We use the JavaScript logical &amp;&amp; operator to conditionally render the h4 element. This is referred to as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators"><strong><em>short-circuit evaluation</em></strong></a> and it works because in JavaScript, true &amp;&amp; expression always evaluates to expression, and false &amp;&amp; expression always evaluates to false. Therefore, if the value in this.state.error is true, the h4 element right after &amp;&amp; will appear in the output. If it is false, React will ignore and skip it.</p><p>Lastly, we embed yet another JavaScript expression to display the country details. Since this.state.data is an array, we use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> method to iterate through the elements and render a div for each country. We need to remember to add a key prop since we are iteration over a list. In the div we display the details about the country.</p><h4>Displaying Loading Indicator</h4><p>Since the API takes some time to return the results, we can improve the user experience of our app by displaying a loading indicator when we are fetching the data. We will use this.state.loading to determine when to display the loading indicator.</p><p>We will update the handleSubmit method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dc7eZsTiK-E3TJRI3CZkqA.png" /></figure><p>Before we make the asynchronous call to the API, we will update this.state.loading to true. Then we will make our API call, and whether it resolves or rejects, we will update this.state.loading back to false.</p><p>In the render method, we <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring">destructure</a> loading from this.state and use it to conditionally render the &lt;h5&gt;Loading...&lt;/h5&gt; element. We also update the error and country info to render only when loading is false (i.e. !loading).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCnefXFqp5BJp-K3In5QBg.png" /></figure><h4>Displaying the languages which are spoken in a country</h4><p>Our API returns the languages spoken in a country as an array. In order to display these languages on our UI, we need to map through them. This might make our render method too long and complex. We can thus split our render method into several small render methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGU1FotieUiOZ5VtY09bew.png" /></figure><p>Instead of adding the JSX to render the languages directly in the render method, we call a custom method this.renderLanguages() and pass in the languages to display. Here is the method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCyBaOi35atNkcC3rhv3vg.png" /></figure><h4>One last thing</h4><p>As a best practice, we would like to disable the submit button by default when the input is empty and only enable it once a user types in some text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsnPrdsNvLP4xfRCZCGFiA.png" /></figure><p>The disabled prop is a Boolean attribute in HTML. Unlike HTML, JSX allows for the value of a Boolean attribute to be explicitly set to either true or false. The value of the disabled prop on our button will, therefore, be set to the result of the expression country.length === 0. The button will thus be disabled when the input is empty and enabled otherwise.</p><p>Here is the entire code for this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d85da082132bcf4348646cf9c8418992/href">https://medium.com/media/d85da082132bcf4348646cf9c8418992/href</a></iframe><p>This is part five in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=122c467ace0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript to React 4 — Working with Forms]]></title>
            <link>https://medium.com/@sandeantony/javascript-to-react-4-working-with-forms-d379c83536f?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/d379c83536f</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[controlled-component]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Sun, 03 Mar 2019 18:35:43 GMT</pubDate>
            <atom:updated>2019-04-27T17:30:15.676Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript to React 4 — Working with Forms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/95YRwf6CNw8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément H</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>This is the fourth in a series of posts which cover the introductory concepts in React.</em></p><p>HTML form elements work a little bit differently from other DOM elements in React because form elements naturally keep some internal state. In HTML, form elements such as &lt;input&gt;, &lt;textarea&gt;, and &lt;select&gt; typically maintain their own state and update it based on user input. In React, when working with class components, the mutable state is typically kept in the state property of the component and only updated using <a href="https://reactjs.org/docs/react-component.html#setstate">setState()</a>.</p><p>When working with forms in React, we can decide to use our form elements like traditional HTML form elements, i.e. allow them to store and update their own state. In this case, we will need to retrieve the values directly from the form elements whenever we need to use them in our application. Alternatively, we can decide to let React manage the state of our form elements in this.state and React will be in charge of synchronizing the component’s internal state with the values in the form elements.</p><p>React has special terms used to describe these two ways of working with forms. A form element that manages its own state is referred to as an “<strong>uncontrolled component</strong>” whereas a form element whose state is managed by React is referred to as a “<strong>controlled component</strong>”.</p><blockquote>In a controlled component, form data is handled by a React component. <br>In an uncontrolled component, form data is handled by the DOM itself.</blockquote><h3>Uncontrolled Components</h3><p>We shall start close to HTML, by looking at how to work with form elements that manage their own state.</p><p>In order to learn how to work with uncontrolled components in React, we shall create a new file named uncontrolledform.html. In the head section of the file, we load React, ReactDOM and Babel (in that order) using their CDN links. In the body section, we have an empty div with an id of root where we shall render our React app. We shall write our code inside the &lt;script&gt; tag as before. Here is how our code looks like so far:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0e9fa1361bbaec64f64a96e09865d38/href">https://medium.com/media/a0e9fa1361bbaec64f64a96e09865d38/href</a></iframe><p>When working with uncontrolled components, we need a way to get the form values from the DOM to use them in our React components. In React we can <a href="https://reactjs.org/docs/refs-and-the-dom.html">use a ref</a> to get form values from the DOM.</p><h4>Refs</h4><p>Refs provide a way to access DOM nodes or React elements created in the render method.</p><p>Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQhW7ILHjn1ojrFj2eY8kw.png" /></figure><p>In the snippet above, we create a class component named UncontrolledForm. In the constructor() method, we create a ref to store a reference to the “Name” &lt;input&gt; DOM element.</p><p><strong>NOTE:</strong> The React.createRef() API was introduced in React version 16.3. If we were using an earlier release of React, we would use <a href="https://reactjs.org/docs/refs-and-the-dom.html#callback-refs">callback refs</a> instead.</p><p>Notice also how we use this.nameInput to define our nameInput ref as an instance property. This makes it possible for us to reference the ref throughout the class.</p><p>In the render() method, we tell React that we want to associate the &lt;input&gt; HTML element with the nameInput ref that we created in the constructor. When a ref is passed to an element in render, a reference to the DOM node becomes accessible on the current property of the ref, in our case as this.nameInput.current. React will assign the DOM element to the current property when the component mounts, and assign it back to null when it unmounts. ref updates happen before componentDidMount or componentDidUpdate lifecycle methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TipfBQz9eYXhGV-rUChHJQ.png" /></figure><p>The snippet above shows how we can access the value of the name input using the ref. In the render() method, we add an onSubmit event handler to the &lt;form&gt; element. This will be triggered when the form is submitted. We bind the handleSubmit method in the constructor in order to access the correct this. Inside the handleSubmit() method, we first call event.preventDefault() method to prevent a full page reload. We log out to the console the value of the name text input by accessing it from this.nameInput.current.value.</p><p>In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, we often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, we can specify a defaultValue attribute instead of value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVCVTPzaxgjZee9iE4WwKA.png" /></figure><p>Likewise, &lt;input type=&quot;checkbox&quot;&gt; and &lt;input type=&quot;radio&quot;&gt; support a defaultChecked attribute, whereas &lt;select&gt; and &lt;textarea&gt; support a defaultValue attribute.</p><p>Here is the full code for this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0edcde1ee97bdf273f1b5fb6c2924bfe/href">https://medium.com/media/0edcde1ee97bdf273f1b5fb6c2924bfe/href</a></iframe><p><strong>SIDE NOTE:</strong> The UncontrolledForm component above could also be written as a function component instead like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfam9z2Cnd6O-jh4qFm4nQ.png" /></figure><h3>Controlled Components</h3><p>In most cases, it is recommended to use controlled components to implement forms. In controlled components, React state is the “single source of truth” as the React component that renders the form also controls what happens in that form on subsequent user input.</p><p>For example, we can write the form in the previous example as a controlled component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuKFQpnS7VON9A9BiCwFbQ.png" /></figure><p>The main difference is that the controlled input accepts its current value as a prop and has an onChange event handler to update that value when the user types in the input.</p><p>In the constructor() method, we add a name property to state that will keep track of the current value of our text input. We also bind this to our new handleChange method.</p><p>Whenever the value of the input changes (this happens when we type into the input field), the this.handleChange handler is called. This updates the value of this.state.name using the setState() method and sets the new value to the contents of the input field. Calling setState() triggers a re-render and the value of the input is updated to the current value of this.state.name. Now the component’s state (data) and the UI (value displayed in the input) are always in sync, with the React state being the only source of truth.</p><p>Here is the full code for this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98bd45d5b59ba0dadf4e46e84d124fac/href">https://medium.com/media/98bd45d5b59ba0dadf4e46e84d124fac/href</a></iframe><h4>Other form elements</h4><p>We shall go ahead and see how to work with the &lt;input type=&quot;checkbox&quot;&gt;, &lt;input type=&quot;radio&quot;&gt;, &lt;select&gt; and &lt;textarea&gt; form elements as controlled elements.</p><p>Here is the updated code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/537ddeff155eb9288779531bc4b6a690/href">https://medium.com/media/537ddeff155eb9288779531bc4b6a690/href</a></iframe><p>We added three checkboxes, two radio buttons, a select dropdown, and a textarea. We added a name prop to the text input, radio buttons, select dropdown, and textarea so that we can be able to re-use one onChange event handler and dynamically update different values in the state. In the handleChange method, we use the ES6 <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names">computed property name</a> syntax to update the state key corresponding to the given input name obtained from event.target.name.</p><p>If we want our form elements to start off with some defaults, then we initialize their corresponding values in the state e.g. the CSS language checkbox will start off selected while the select will have the “intermediate” option start off selected.</p><p>This is part four in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d379c83536f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript to React 3 — Handling Events]]></title>
            <link>https://medium.com/@sandeantony/javascript-to-react-3-handling-events-eb96954a620b?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb96954a620b</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[binding]]></category>
            <category><![CDATA[events]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 14:19:58 GMT</pubDate>
            <atom:updated>2019-04-27T17:29:35.797Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript to React 3 — Handling Events</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/95YRwf6CNw8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément H</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>This is the third in a series of posts which cover the introductory concepts in React.</em></p><p>Handling events with React elements is very similar to handling events on DOM elements. The two main syntactic differences are:</p><ol><li>React events are named using camelCase, rather than lowercase.</li><li>With JSX, we pass a function as the event handler, rather than a string.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*ZJaIOKv2jK-6PHKGJ9V6oQ.png" /></figure><p>We are going to build on top of our number Counter app that we created <a href="https://medium.com/@sandeantony/javascript-to-react-2-state-and-lifecycle-8b9e6d9c9d94">previously</a>. We will increase the rate at which our number in the state is updated by reducing the delay parameter passed into the setInterval() method to 1 millisecond. We want our app to behave like a <em>lottery machine</em>. It will display a really quick counter that increments from 0 onwards. We will then add a button that gets a lucky number from our lottery when clicked. When we click the button, we will grab the current value of this.state.number and display it in an unordered list on the page.</p><p>We shall first go through all the new concepts before we see how our new code looks like. Feel free to come back here later to check the explanation of the code for better understanding.</p><p>The first change we shall make to our app is to adjust the delay on the setInterval() method to 1 ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBQ1hlX_3WTUN7nQp-N2lA.png" /></figure><p>We will then add a new property to our this.state object in the constructor() to store our lucky numbers. It will be an array since we want to store several numbers. We shall name it luckyNumbers and we shall instantiate it with an empty array [].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*V3XRMQ7vtcf7Ij4t8mqKKw.png" /></figure><p>Next, we shall add a button to our render() method. When we click this button, we want to grab the current value in this.state.number and add it to the this.state.luckyNumbers array.</p><p>This requires us to add an onClick event handler to our button. We shall pass a function called getLuckyNumber to the event handler that will be called when the user clicks the button. Since the getLuckyNumber function will be defined on the class, we have to access it as this.getLuckyNumber.</p><p>Notice that, unlike in HTML, we do not pass this.getLuckyNumber() to the event handler (with the invocation brackets ()). Passing this.getLuckyNumber() will invoke this method immediately when the component’s render() method is called. This is not what we want, as we only want to invoke this function when the button registers a click event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ho5xv6NNxi5ALh7OPV-kIw.png" /></figure><p>Notice that we adjusted the return value and wrapped the &lt;h2&gt; and &lt;button&gt; elements in a &lt;div&gt; element. We do this since React requires that adjacent JSX elements must be wrapped in an enclosing tag.</p><p><strong>NOTE:</strong> If wrapping the adjacent JSX elements in an extra &lt;div&gt; element will result in the HTML being invalid or break the CSS styling of the UI, then use <a href="https://reactjs.org/docs/fragments.html"><strong>React Fragments</strong></a> to group the list of children to be rendered without adding extra nodes to the DOM.</p><p>Let us look at the implementation of the getLuckyNumber() method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzRNnuIsczAu2EMR6hmePg.png" /></figure><p>This method resembles the tick() method that we wrote earlier. We are updating the luckyNumbers property in the state. We pass an updater function as the first parameter to the setState method since we need to access the previous state. We use the concat() method that is inherent in JavaScript arrays to add the current number in the state to the luckyNumbers array. The reason why we use concat() and not push() is because of the main difference between these two methods: whereas push() modifies the existing array, concat() does not change the existing array, but instead returns a new array. This is important in React since we do not want to mutate the state.</p><p>Once we call this.setState(), React will re-render the component and update the application’s UI.</p><p>However, if we open our app in the browser at this moment and click on the button, we see the following error on the browser console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*He0szCcTmAZF0T2D0tuW8g.png" /></figure><p>this is undefined!</p><p>Since setState() is a method provided on the React class component, we need to make sure that when we call this.setState(), the this keyword actually points to the class. When we create a class in JavaScript, the class constructor() method always has the this keyword correctly set to point to the class. React also makes sure that the this keyword is correctly set to point to the class in all its lifecycle methods (e.g. componentDidMount() and componentWillUnmount()) and also in the component’s render() method.</p><p>However, we are responsible for making sure that the this keyword correctly points to the class in any of the custom methods that we add to our component. Otherwise, it will be undefined by default (in strict mode) as we just saw.</p><p>In JavaScript, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind</a> method is used to set the value of a function&#39;s this regardless of how the function is called. Calling fn.bind(someObject)creates a <strong>new function</strong> with the same body and scope as fn, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.</p><p>With this in mind, we can adjust our event handler and call our custom method with .bind() passing in this as the first argument of bind:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cVVdsNntTZ0aTg4-023HQ.png" /></figure><p>With this change, clicking the button no longer results in an error. This is because our onClick event handler now receives a new function with the same body and scope as the getLuckyNumber function, but where this occurs in the original function, in the new function it is permanently bound to the correct this keyword that references the class.</p><p>Despite the fact that this approach of binding in the render() method works fine, the problem with this syntax is that a new function is created each time the Counter component renders. In most cases, this is fine. However, the best practice is to only create the new function once for the lifetime of the component. In order to do this, we shall instead bind our function in the constructor() method instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qcne9buD5DOPBcmprtUa9w.png" /></figure><p>Calling <em>this</em>.getLuckyNumber = <em>this</em>.getLuckyNumber.bind(<em>this</em>); in the constructor binds this to the function and assigns the new bounded function back to a class method with the same name. We can then use this method as many times in the render() method and each time we shall have the correct this referenced in the method. Unlike previously, our newly bound method is only created once during the lifetime of the component when the constructor() method is called.</p><p>Generally, if we pass an event handler to an event attached to a JSX element, such as onClick={this.getLuckyNumber}, we should bind that method in the constructor() method.</p><p><strong>NOTE:</strong> This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if we refer to a method without () after it, such as onClick={this.handleClick}, we should bind that method. However, most developers are annoyed by the fact that they always have to bind these methods. There are two ways to get around this:</p><ol><li>Using arrow functions in the callback (this is not recommended as it suffers from the same issues as binding in the render() method).</li><li>Using the <strong><em>experimental</em></strong> <a href="https://babeljs.io/docs/en/babel-plugin-proposal-class-properties">public class fields syntax</a> (this is experimental syntax and additional setup is needed to use it).</li></ol><p>For now, we shall stick to binding our event handlers in the constructor() method.</p><h4>Displaying the lucky numbers</h4><p>When we click the button, we get the lucky numbers added to the state, but so far there is no way of viewing the lucky numbers on the UI. Let us add an unordered list to the render() method below the button to display the lucky numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f27ELv_-m9quskyDoc0fkA.png" /></figure><p>As we mentioned when introducing JSX, we can embed any JavaScript expression in JSX by wrapping it in curly braces. We want to dynamically list the lucky numbers from our state.luckyNumbers array. We will use JavaScript’s map() array function to return a new array of JSX elements with each number in the array wrapped in a JSX &lt;li&gt; element that will be rendered on the screen. Since we call setState() every time the button is clicked, the render method will be called again with the new array and the list will be updated.</p><h4>Lists and Keys</h4><p>However, if we open our app in the browser at this moment and click on the button, we see the following error on the browser console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*VCFZNzWUnXi10DmF3vBNjQ.png" /></figure><p>The warning we get says that a key should be provided for list items. A “<strong>key</strong>” is a special string attribute we need to include when creating lists of elements.</p><p>Keys help React to identify which items in the list have been changed, have been added, or have been removed. Keys should be given to the elements inside the array to give the elements a stable identity. The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often we would use the unique IDs from our data as keys. When we don’t have stable IDs for rendered items, we may use the item’s index as a key as a last resort (though this is not recommended). Keys used within arrays should be unique among their siblings.</p><p>Let’s assign a key to our list items inside this.state.luckyNumbers.map() and fix the missing key issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RVcoMBbvRFO9Ca93VV9CA.png" /></figure><p>Here is the complete code for our application up to this point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3dc0df978f0629afb26836864f501ab/href">https://medium.com/media/c3dc0df978f0629afb26836864f501ab/href</a></iframe><h3>Passing Arguments to Event Handlers</h3><p>Inside a loop, it is common to want to pass an extra parameter to an event handler. For example, if we want to delete a lucky number from our list, we need to pass the number to delete in our event handler. We could achieve this using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkRsIVXkngew_5STjEeD3A.png" /></figure><p>The JavaScript bind function accepts a sequence of arguments after the first this argument, which are passed on to the bound function.</p><p>But we learned previously that binding our event handlers in the render() method is not a good practice. Let us look at how we pass arguments to event handlers when the binding is done in the constructor() method:</p><p>First, we shall update the render() method of our component and add a button alongside each lucky number on our list. Clicking this button will remove the lucky number from the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXZpdblnsppYrWRxQXascw.png" /></figure><p>Next, we shall bind the new event handler in the constructor() method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_LA9SkRCFDAen-wLhWzuQ.png" /></figure><p>Notice, however, how we set our event handler using this.deleteLuckyNumber(number). The main difference here is that we use the function invocation brackets () because we need to pass the number argument to our handler. The effect of doing this is that immediately our delete button is displayed on the UI, our this.deleteLuckyNumber(number) method will be executed. This is not what we want as we only want to execute this method when the delete button is clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ew1_uDr_TED6y6puFQz56A.png" /></figure><p>In order to fix this problem, we shall use a feature of JavaScript functions that allow them to be returned from other functions. When we return a function from another function, we must manually invoke both the outer and the inner functions for them to be executed. Therefore, the returned inner function will only be executed when the button is clicked and it will receive the click event through the event object.</p><p>Since our deleteLuckyNumber initially received the clickedNumber argument, this argument will be in scope and can, therefore, be accessed whenever the inner returned function is executed.</p><p>In order to remove the clicked lucky number from the state, we update the luckyNumbers property of state with a new array that does not include the deleted number. To obtain this new array, we make use of JavaScript’s array <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">filter()</a> method and test for all numbers in this.state.luckyNumbers which are not equal to the clickedNumber. Remember, we should not mutate the state. The filter() method creates a new array with all elements that pass the test implemented by the provided function.</p><p>Here is the complete code for our application up to this point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2074aafb905bfae1042ee9bedad7cbfa/href">https://medium.com/media/2074aafb905bfae1042ee9bedad7cbfa/href</a></iframe><p>We have only looked at the onClick event. Look at all the events supported in React by visiting this link <a href="https://reactjs.org/docs/events.html#supported-events">https://reactjs.org/docs/events.html#supported-events</a>.</p><p>This is part three in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb96954a620b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript to React 2 — State and Lifecycle]]></title>
            <link>https://medium.com/@sandeantony/javascript-to-react-2-state-and-lifecycle-8b9e6d9c9d94?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b9e6d9c9d94</guid>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Sat, 26 Jan 2019 18:01:07 GMT</pubDate>
            <atom:updated>2019-04-27T17:28:42.356Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript to React 2 — State and Lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/95YRwf6CNw8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément H</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>This is the second in a series of posts which cover the introductory concepts in React.</em></p><h3>React Props</h3><p>In the <a href="https://medium.com/@sandeantony/from-javascript-to-react-basics-ab4735333666">previous post</a>, we looked at React props. Props stand for “properties” and they are arguments that are passed to a React component. Props are therefore a way of passing data into a React component.</p><p>One important point to remember is this: <strong>Props are Read-Only</strong>. Once we declare a component as a function or a class, it must never modify its own props.</p><blockquote>Props are Read-Only</blockquote><p>Since application UIs are dynamic and change over time, React makes use of the component’s “<strong>state</strong>”. State allows React components to change their output over time in response to user actions, network responses, or anything else, without violating this rule.</p><p>In order to have React manage the application state, we shall create our React component as a class and not as a function as we have been doing before.</p><p><strong>NOTE:</strong> At the time of writing this, a new feature called <a href="https://reactjs.org/docs/hooks-intro.html"><strong>React Hooks</strong></a> is being introduced that will allow us to use state without writing a class.</p><p>React components that are created as a class are referred to as <strong>Class Components</strong>, while those that are created as a function are known as <strong>Function Components</strong> because they are literally JavaScript functions.</p><h3>Class Components</h3><p>Class components are React components which are created using JavaScript classes. JavaScript classes were introduced in ECMAScript 2015 (ES6), and are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance model.</p><p>Class components in React extend the React.Component base class which is provided by React. A class component is required to have a method by the name render() which returns the React element that should be rendered to the DOM.</p><p>This is how our previous code looks like when we convert the GreetingComponent and App components into class components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fb6fa332799c65446a0145d34dcb302/href">https://medium.com/media/2fb6fa332799c65446a0145d34dcb302/href</a></iframe><p>We can convert a function component like GreetingComponent to a class component in five steps:</p><ol><li>Create an <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes">ES6 class</a>, with the same name, that extends React.Component.</li><li>Add a single empty method to it called render().</li><li>Move the body of the function into the render() method.</li><li>Replace props with this.props in the render() body.</li><li>Delete the remaining empty function declaration.</li></ol><p><strong>NOTE:</strong> Function components are simpler than class based components and will benefit from future React performance optimizations specific to these components. So it is recommended to write most of our React components as function components.</p><h3>React State</h3><p>Now that we have seen how to create a class component, let us go ahead and see how to work with React state.</p><p>We shall use an example of a UI that displays a number starting from 0 and increments it every second.</p><p>Before we write our example code, here are a few important concepts to understand about React and JavaScript classes in general.</p><h3>React Component Lifecycle Methods</h3><p>Every React component goes through a series of stages during its lifetime, from when it is rendered to the DOM to when it is removed from the DOM. These stages are collectively referred to as the <strong>Lifecycle</strong> of the component.</p><p>Each component has several “<strong>lifecycle methods</strong>” that we can override to run code at particular times in the process. These methods are provided to us by React to allow us to execute custom actions at each of the different stages of the component’s lifecycle.</p><p>A component’s lifecycle is divided into the following three main stages, and particular lifecycle methods will be automatically called by React at these stages:</p><p><strong>1. Mounting</strong></p><p>The lifecycle methods at this stage are called when an instance of a component is being created and inserted into the DOM. Among them, we shall introduce three: constructor(), render() and componentDidMount() methods.</p><p><strong>2. Updating</strong></p><p>An update to a React component can be caused by changes to props or state. The lifecycle methods at this stage are called when a component is being re-rendered.</p><p><strong>3. Unmounting</strong></p><p>The only lifecycle method at this stage is called when a component is being removed from the DOM. We shall introduce it here: the componentWillUnmount() method.</p><p>Here is a <a href="http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/">React lifecycle diagram cheat sheet</a>.</p><h3>constructor()</h3><p>The constructor method is a special method available to all JavaScript classes and it is used for creating and initializing an object created with a class. In React, the constructor() method is the first method that is called before the component is mounted.</p><p>Since we use the extends keyword when declaring our React class component, our component becomes a child of the React.Component class. If there is a constructor present in our subclass, it needs to first call super() before using “this”. In order to access the props passed to our component using this.props, we need to call super(props) before any other statement in the constructor.</p><p>Since the constructor is the first method called when the component is mounted, it is the right place to initialize the component’s <strong>state</strong>. To do so, we just assign an object to this.state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*WYk6UMX5MbovHiG82edS5A.png" /></figure><p><strong>NOTE:</strong> If we are not initializing state or binding methods (more on this later), we don’t need to implement a constructor for our React component.</p><h3>render()</h3><p>The render() method is the only method which is required to be present in a React class component. The render() method must have a return statement that describes what we want to see on the screen. We typically return React elements from the render() method that are created using JSX. The elements can either be a representation of native DOM elements (e.g. &lt;div /&gt;), or user-defined composite components (e.g. &lt;MyComponent /&gt;). We can return null from the render() method in case we do not want to render anything. We can also return arrays, strings, numbers or booleans from the render() method. The render() method should not modify the component state (i.e. it should be pure).</p><p>Below is an example of a render() function that returns a &lt;h2&gt; native DOM element with the value of the number key in the this.state object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*vd3NV1ICFDxCUS83p-Nq-w.png" /></figure><h3>componentDidMount()</h3><p>The componentDidMount() method is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If we need to load data from a remote endpoint, this is a good place to instantiate the network request.</p><p>This method is a good place to set up any subscriptions. If we do that, we need to remember to unsubscribe in componentWillUnmount().</p><h3>componentWillUnmount()</h3><p>The componentWillUnmount() method is invoked immediately before a component is unmounted and destroyed. We should perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().</p><p>We have gone through quite a number of new concepts in order to understand how to work with React state. As we learned before, React state contains data specific to a given React component that may change over time.</p><p>One important point to remember is this: we should <strong>never mutate (change) </strong><strong>this.state directly</strong>. We should always treat this.state as if it were immutable.</p><p>Now the question is, if state contains data that may change over time, and we are not allowed to mutate state, how do we update it?</p><blockquote><strong>Never mutate </strong><strong>this.state directly</strong></blockquote><h3>setState()</h3><p>React provides a method on the class component called setState() that allows us to update the component’s state. The setState() method does one more thing after updating the value of this.state, it tells React that this component and its children need to be re-rendered with the updated state. This is really important as React will only update the parts of the UI that are affected by the changes in the state and all the other DOM elements will remain unchanged. This results in smoother user experience for the users of our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*7iFeYBVAajA8CmaFg23fSQ.png" /></figure><p>The first argument to the setState()method is an updater function with the signature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*i1tFuq2h4Fv-YCtTvQZdvQ.png" /></figure><p>prevState is a reference to the previous state. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from prevState and props. For instance, suppose we wanted to increment our number counter in state by 1, we could use the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*gIdLK7JNDuW8XIlWluMy1w.png" /></figure><p>We used an <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a> above, but it also works with regular functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*sob71q1V4l9aHLZIhdXtxw.png" /></figure><p>We may optionally pass an object as the first argument to setState() instead of a function. This performs a shallow merge of the passed object into the new state, e.g., we may adjust our number in state as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*5Axg0j5ItC_fs7CCDVyiow.png" /></figure><p>The second argument to the setState()method is an optional callback function that will be executed once setState is completed and the component is re-rendered.</p><p>Now that we understand the concepts surrounding working with component state, let us write our example of a UI that displays a number starting from 0 and increments it every second.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/398ee02ebd87ebc012d31f652668e177/href">https://medium.com/media/398ee02ebd87ebc012d31f652668e177/href</a></iframe><p>In the code snippet, we create a React class component named Counter. We then assign the initial component state by setting this.state in the component’s constructor() method. We initialize a property called number to a value of 0. This is the value that we display in the UI inside a &lt;h2&gt; tag in the render() method.</p><p>We want to set up a timer using the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval">setInterval</a> method whenever the Counter component is rendered to the DOM for the first time. This is called “mounting” in React.</p><p>We also want to clear that timer using the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval">clearInterval</a> method whenever the DOM produced by the Counter component is removed. This is called “unmounting” in React.</p><p>We shall use the componentDidMount() and the componentWillUnmount() React lifecycle methods.</p><p>We can add additional fields to the class manually if we need to store something that doesn’t participate in the data flow by adding them as properties to the this object (like our this.interval).</p><p>We can also add additional custom functions to the class and these class functions can be accessed as methods on the this object (like our this.tick() method).</p><p>In the componentDidMount() lifecycle method, we create a timer that runs every second (1000 milliseconds) and calls our this.tick() method. Since we need to remove this timer when the Counter component unmounts, we will assign it to a property on the class called interval.</p><p>In the componentWillUnmount() lifecycle method, we will remove the timer using clearInterval(this.interval) function.</p><p>Finally, the tick() method that the Counter component will run every second uses this.setState() to schedule updates to the component’s local state.</p><p>Now our number is updated every second.</p><p>Let’s quickly recap what’s going on and the order in which the methods are called:</p><ol><li>When &lt;Counter /&gt; is passed to ReactDOM.render(), React calls the constructor of the Counter component. Since Counter needs to display a number, it initializes this.state with an object including a number with a value of zero. We will later update this state.</li><li>React then calls the Counter component’s render() method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the Counter’s render output.</li><li>When the Counter output is inserted in the DOM, React calls the componentDidMount()lifecycle method. Inside it, the Counter component asks the browser to set up a timer to call the component’s tick() method once every second.</li><li>Every second the browser calls the tick() method. Inside it, the Counter component schedules a UI update by calling setState() with an updater function that increments the previous number in the state by 1. Thanks to the setState() call, React knows the state has changed and calls the render() method again to learn what should be on the screen. This time, this.state.number in the render() method will be different, and so the render output will include the updated number. React updates the DOM accordingly.</li><li>If the Counter component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle method so the timer is stopped.</li></ol><p>This is part two in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b9e6d9c9d94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From JavaScript to React — Basics]]></title>
            <link>https://medium.com/@sandeantony/from-javascript-to-react-basics-ab4735333666?source=rss-8885f7052217------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab4735333666</guid>
            <category><![CDATA[jsx]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Antony Sande]]></dc:creator>
            <pubDate>Sat, 26 Jan 2019 15:43:59 GMT</pubDate>
            <atom:updated>2019-04-27T17:27:37.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>From JavaScript to React — Basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/95YRwf6CNw8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément H</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>This is the first in a series of posts which cover the introductory concepts in React.</em></p><p>Before we begin, I would like all of us to read this article from Brad Frost <a href="https://the-pastry-box-project.net/brad-frost/2014-january-28">https://the-pastry-box-project.net/brad-frost/2014-january-28</a>. I write these posts with the assumption that I am explaining React to an earlier version of myself, at the time when I didn’t know what I know now. I will, therefore, try and provide as much context as I can.</p><p>So, you are now comfortable with JavaScript, and you are ready to move on to using a tool. You think that React is a cool fit because of the hype/what you have heard. This series of workshop posts will help you to learn the basics of React and why so many people love and use it. You are encouraged to write and run all the code snippets as we go through with the workshop.</p><p>React is a front-end JavaScript library for building user interfaces. It was built and is maintained by Facebook.</p><p>This is a beginner workshop meant to teach the very basics of React. The goal of this workshop is to gain an understanding of the fundamental concepts in React and how React works.</p><p>We shall code in a self-contained file named index.html which will be loaded up directly in our browser. This is in order to avoid distractions and focus on learning React.</p><p>We shall kick off with a simple “Hello World” app written in vanilla JavaScript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84609d367a3e854a4c353221a18d50b2/href">https://medium.com/media/84609d367a3e854a4c353221a18d50b2/href</a></iframe><p>In the code snippet:</p><ol><li>We create a div with an id of root.</li><li>We add a script tag with our JavaScript code. NOTE: In HTML5, the type=&quot;text/javascript&quot; attribute is optional. We select the div from the DOM and store it in a variable called rootElement.</li><li>We then create an h1 DOM element using createElement and store it in a variable called element.</li><li>We set the textContent of the h1 to “Hello World” and give it a class of “container” (these are properties).</li><li>We add the h1 element to our root div element.</li></ol><p>If we save this file and open it in our browser, we should see the text “Hello World” displayed on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*XCyAkYmf5fVtqT1v7g-rCQ.png" /></figure><p>Now we want to achieve the same result using React and see the difference between the two.</p><h3>React Elements</h3><p>React elements are the smallest building blocks of React apps and are used to describe what you want to see on the screen. Unlike browser DOM elements, however, React elements are simply plain JavaScript objects.</p><p>Similar to vanilla JavaScript, React also provides a createElement method, which allows us to add properties to our element, and provides a render method that allows us to append the elements to the DOM.</p><p>We will update our code to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5df910df37de218503641485f73d7f9/href">https://medium.com/media/d5df910df37de218503641485f73d7f9/href</a></iframe><p>First, we include the React and ReactDOM scripts in the head tag. We link to the CDN (Content Delivery Network) scripts for React version 16. We could also download the scripts and save them locally in order to access them without an internet connection.</p><pre>&lt;script crossorigin src=&quot;https://unpkg.com/react@16/umd/react.development.js&quot;&gt;&lt;/script&gt;</pre><pre>&lt;script crossorigin src=&quot;https://unpkg.com/react-dom@16/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;</pre><p><strong><em>SIDE NOTE:</em></strong> Notice that we are using two separate libraries, React and ReactDOM. The React package exposes APIs for defining React elements, whereas the ReactDOM library is what is referred to as a “renderer”, and it is where most of the implementation of React lives. React comes with several renderers, including react-dom, for rendering our React elements on the browser, react-dom/server, for rendering our React elements on the server, react-native, for rendering our React elements on native mobile devices as Android or iOS apps, e.t.c.</p><p>In this snippet, after selecting the div from the DOM and storing it in the rootElement variable, we then use React’s createElement method to create a new element. This method takes at least 3 arguments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*3HH8PZ_fzCCHjfXpDwN2nw.png" /></figure><ol><li>The type of the element to create. Here we provide the h1 tag name string.</li><li>An object containing the attributes / properties passed to the element. Here we provide the className. These are referred to as props in React.</li><li>The content to display inside the tag. Here we pass the text content “Hello World”. This is referred to as children in React, and they are also categorized as props.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*cR4e64G780S9rqUqdxIlVQ.png" /></figure><p>The render method in ReactDOM is used to render the element into the DOM inside the supplied container. Here we are rendering our created element inside the rootElement div.</p><h4>What does React.createElement return?</h4><p>If we log out the value of element:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5zt2T7qInosJcH1Tc7fhTg.png" /></figure><p>then open the developer console and expand the object logged, we see that the props property contains the className as well as the text content with the key children:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*9EM_zXfaid70CfLVX7_I7g.png" /></figure><p>Since the text content we provided as the third element to React.createElement is combined in the props object, we can as well supply it under the children key in the second argument of React.createElement and we will get the same output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwtJ2ztr1eWVoSQMr6_7IA.png" /></figure><p>If we need to display several children, we can pass them to the children prop as an array and they will each be rendered to the DOM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PeHmqhh0zruwC60IjYe1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*e_PwECdIs64e2X5B7yC3Yw.png" /></figure><p>We can also pass another React element as one of the items in the children array, thus enabling us to build nested DOM trees.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9ea6394b8ec4a70388c3f0e4a4b2b5d/href">https://medium.com/media/e9ea6394b8ec4a70388c3f0e4a4b2b5d/href</a></iframe><p>The snippet above shows two separate React elements: helloElement and worldElement. The wrapperElement is what we render to the DOM and we are passing the helloElement and worldElement as its children.</p><p><strong>NOTE:</strong> We pass null as the second argument to React.createElement when creating the helloElement. We do this because we do not want to pass any props/attributes to the element.</p><h3>React Components</h3><p>The User Interface (UI) of a React app is built by composing different React components together.</p><blockquote>A React component is a function or a class which optionally accepts inputs (called “props”) and returns a React element.</blockquote><p>We can now create components by wrapping our React elements into functions.</p><p><strong>NOTE: Always start component names with a capital letter</strong>, as React treats components starting with lowercase letters as DOM tags.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06bf91cb948f652bc91488e1ac77eae0/href">https://medium.com/media/06bf91cb948f652bc91488e1ac77eae0/href</a></iframe><p>In this snippet, we now have one React component: GreetingComponent. This component simply returns one of the React elements we had previously. The only difference is that the content passed as the third argument is not hard-coded, but instead is passed in as the text key of the props parameter.</p><p>We will still make use of the React.createElement method to get the returned element from this component.</p><p>Apart from the type parameter of the React.createElement method being a tag name string as we saw in the first example, it can also be a React component (a function or a class).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHltuGp6XGhuDxm_TKhtpw.png" /></figure><p>We, therefore, pass the GreetingComponent function as the first argument and the “prop” text as the second argument.</p><h3>Introducing JSX</h3><p>JSX is a syntax extension to JavaScript that is used with React to describe what the UI should look like. JSX provides syntactic sugar for the React.createElement(component, props, ...children) function (<strong><em>syntactic sugar</em></strong> is syntax within a programming language that is designed to make things easier to read or to express. It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.). We can use JSX to simplify creating React components, especially when dealing with deeply nested DOM trees.</p><p>JSX syntax resembles HTML, but <strong>it is not HTML</strong>. React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. We shall introduce how to work with JSX.</p><p>Since the JSX specification is not intended to be implemented by JavaScript engines, browsers do not understand it and therefore JSX will not work directly on the browser. We, therefore, need to transform JSX into standard JavaScript for the browsers to understand it. This transformation is referred to as <strong>transpilation</strong> and it is done using a <strong>transpiler</strong>.</p><p>There are several transpilers that conform to the JSX syntax, and we shall use one of them called <strong>Babel</strong>. Babel is a JavaScript compiler that can transpile JSX and output normal JavaScript that runs in the browser.</p><p>In order to use Babel, we need to include the standalone version of Babel in the head of our HTML code. We shall use the following CDN link. We could also download it and use it locally.</p><pre>https://unpkg.com/babel-standalone@6.15.0/babel.min.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOPL9ugMcZ1G_eyXvYhGCA.png" /></figure><p>It is also important to write our JavaScript code inside a script with type=&quot;text/babel&quot;.</p><p>This is how our code looks like now with the JSX syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a9dd7a56fc7e2e09ebc1c5c8d28a119/href">https://medium.com/media/3a9dd7a56fc7e2e09ebc1c5c8d28a119/href</a></iframe><p>In the snippet, we have replaced the return value of the GreetingComponent React function component with &lt;h2&gt;{props.text}&lt;/h2&gt;. h2 is our JSXElementName while {props.text} is the JSXChild that will be rendered as the content of the h2. Since this JSX element starts with a lowercase letter, it will render an HTML h2 tag to the DOM.</p><p>We created a new React function component called App() that returns the same output as the previous wrapperElement. App() returns a single JSX div element which will render an HTML div element to the DOM (because it begins with a lowercase letter). The div accepts an id attribute using the same syntax as HTML. In React, this is called a <strong>“prop”</strong>.</p><p>Similar to HTML tags, we can nest JSX tags. The div tag contains two children: two &lt;GreetingComponent&gt; JSX tags. Since the GreetingComponent tag name starts with an uppercase letter, React requires the GreetingComponent component (function or class) to be in scope since it will be transpiled to React.createElement(GreetingComponent).</p><p>The first time, React will call the GreetingComponent function and pass it the prop text as the string “Hello”. The GreetingComponent component will then return a &lt;h2&gt;Hello&lt;/h2&gt; element as the result.</p><p>Finally, to render the App() component to the DOM, we pass the &lt;App /&gt; JSX tag to the ReactDOM.render() method. Running this code in the browser will give us the same output as before.</p><h3>A little more JSX</h3><p>We have seen a fair bit of the JSX syntax, but there is more to it.</p><p>We can embed any JavaScript expression in JSX by wrapping it in curly braces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVFX15I44ncpvrTLZjWqhw.png" /></figure><p>We can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gK0VwELnrGs-d1W5isQLIw.png" /></figure><p>Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.</p><p>For example, class becomes className in JSX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ym9VwMO5IOW97FgHxDJ4Aw.png" /></figure><p>We may also use curly braces to embed a JavaScript expression in an attribute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArzLtjE95T4kSF9qUsHqNw.png" /></figure><p>Learn more about JSX from the official React documentation by visiting this link <a href="https://reactjs.org/docs/jsx-in-depth.html">https://reactjs.org/docs/jsx-in-depth.html</a></p><p>This is part one in a series of posts covering the introductory concepts in React.</p><ul><li>Part 1: <a href="http://bit.ly/jstoreact">Basics</a></li><li>Part 2: <a href="http://bit.ly/jstoreact2">State and Lifecycle</a></li><li>Part 3: <a href="http://bit.ly/jstoreact3">Handling Events</a></li><li>Part 4: <a href="http://bit.ly/jstoreact4">Working with Forms</a></li><li>Part 5: <a href="http://bit.ly/jstoreact5">Working with Remote Data</a></li><li>Part 6: <a href="http://bit.ly/jstoreact6">Development Environment</a></li><li>Part 7: <a href="http://bit.ly/jstoreact7">Babel and Webpack</a></li><li>Part 8: <a href="http://bit.ly/jstoreact8">Beyond JavaScript</a></li><li>Part 9: <a href="http://bit.ly/jstoreact9">Create React App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab4735333666" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>