<?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[Byte-sized React - Medium]]></title>
        <description><![CDATA[Brief, visual React tips and tutorials. - Medium]]></description>
        <link>https://medium.com/byte-sized-react?source=rss----12ef1ca9db6e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Byte-sized React - Medium</title>
            <link>https://medium.com/byte-sized-react?source=rss----12ef1ca9db6e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:44:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/byte-sized-react" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is ‘this’ in React?]]></title>
            <link>https://medium.com/byte-sized-react/what-is-this-in-react-25c62c31480?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/25c62c31480</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Thu, 30 Nov 2017 04:51:08 GMT</pubDate>
            <atom:updated>2017-11-30T04:51:07.909Z</atom:updated>
            <content:encoded><![CDATA[<p>And why do we use it all the time?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWU86Q4jxwR7aOu8lGqz8g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/pmhdkgRCbtE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Terrah Holly</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you are jumping into React, you are probably seeing a lot of ‘this’ lately. Let’s dive into what the ‘this’ keyword means in JavaScript and React.</p><h4>The ‘this’ keyword</h4><p>The ‘this’ keyword typically references a JavaScript element depending on the scope or context of its use. Let me give you a few examples for that to set in.</p><h4>Global ‘this’ scope</h4><p>The most straight forward scope is the global scope in your browser. If you open the console in a web browser and run the following…</p><pre>this</pre><p>The browser will return the global Window object…</p><pre>Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, …}</pre><p>Any command that you would run on the Window object you can run with ‘this’ in the global scope.</p><pre>this.alert(‘Hey!’)<br>//Is the same as<br>Window.alert(‘Hey!’)</pre><pre>this.location = ‘<a href="https://medium.com&/#39;">https://medium.com&#39;</a><br>//Is the same as<br>Window.location = ‘<a href="https://medium.com&/#39;">https://medium.com&#39;</a></pre><h4>Function ‘this’ scope</h4><p>This is where things get a little fuzzy and you better have your lexical scope wits about you.</p><p>The value of ‘this’ in JavaScript functions is determined by how a function is called. Methods like call, apply, and bind explicitly set the value of ‘this’ in a function, however if ‘this’ isn’t explicitly set, then ‘this’ will default to the global context.</p><pre>const thisFunction = function () {<br> return this;<br>}<br>//Calling thisFunction() in the browser will return the window object</pre><p>When using strict mode, ‘this’ in a function will refer to it’s explicit value, and if ‘this’ hasn’t been explicitly set then ‘this’ will be undefined.</p><pre>const strictFunction = function() {<br> ‘use strict’;<br> return this;<br>}<br>//Calling strictFunction() in the browser will return undefined since this is not explicitly set with call, apply, or bind</pre><h4>Explicitly setting ‘this’ with call, apply, bind, and the arrow function</h4><p>So how do we explicitly set ‘this’ on a function? The call, apply, and bind methods do this for us.</p><p>The call method on a function accepts an object that ‘this’ will refer to and any other parameters defined in the function. The apply method accepts the object ‘this’ will refer to and an array that contains the parameters reference when defining the function.</p><pre>const object = {<br> a: 5,<br> b: 7<br>}</pre><pre>const thisFunction = function(c, d) {<br> return this.a + this.b + c + d;<br>}</pre><pre>thisFunction.call(object, 12, 4);<br>//will return 28</pre><pre>thisFunction.apply(object, [3, 6]);<br>//will return 21</pre><p>The bind method differs from call and apply in that the bind method attaches an object to a function so that every time the function is called it refers to the bound object.</p><pre>const object = {a: 2, b:3, c:6};</pre><pre>const thisFunction = function() {<br> return this.a + this.b + this.c;<br>}</pre><pre>const bindFunction = thisFunction.bind(object);</pre><pre>bindFunction(); //will return 11</pre><h4>Object context</h4><p>When using ‘this’ in an object, this will refer to the object itself. This makes it easy to refer to an object’s values in the object’s methods.</p><pre>const object = {<br> a: 2,<br> b: 3,<br> thisFunction: function(){<br> return this.a + this.b;<br> }<br>};</pre><pre>object.thisFunction() //returns 5</pre><h4>So what does this mean for React</h4><p>In React component classes we define methods that will refer to class attributes such as props and state. However, for our methods to have access to this.state and this.props we need to bind the React component ‘this’ context to those methods.</p><pre>import React, { Component } from ‘react’;</pre><pre>class App extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.clickFunction = this.clickFunction.bind(this);<br>  }</pre><pre>  clickFunction() {<br>    console.log(this.props.value);<br>  }</pre><pre>  render() {<br>    return(<br>      &lt;div onClick={this.clickFunction}&gt;Click Me!&lt;/div&gt;<br>    );<br>  }<br>}</pre><p>Binding ‘this’ to the class methods enables us to access props and state for the component with this.props and this.state.</p><h4>The Arrow Function</h4><p>As you noticed, binding ‘this’ to your class methods can create a lot of boiler plate. The arrow function introduced in ES6 is a function with the current ‘this’ context already bound to the function. Because of this nice functionality we can use public class fields to automatically bind this to our methods.</p><pre>const myFunction = () =&gt; {<br> return this.props.a + this.props.b;<br>}</pre><pre>//The previous stated myFunction is the same as...</pre><pre>const myFunction = function() {<br>  return this.props.a + this.props.b;<br>}.bind(this);</pre><p>The combination of the arrow function and public class fields proved a clean, declarative way to define our React components.</p><p>In my next post we’ll look at the difference between the .bind(this) boilerplate and public class fields.</p><p>Thanks for reading!</p><p>If you’d like to hear more then subscribe to the weekly newsletter and connect with me <a href="http://treyalexanderdavis.com/">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25c62c31480" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/what-is-this-in-react-25c62c31480">What is ‘this’ in React?</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting React and a REST API with Express]]></title>
            <link>https://medium.com/byte-sized-react/hosting-react-and-a-rest-api-with-express-28f7ba5a4cc4?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/28f7ba5a4cc4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Thu, 26 Oct 2017 23:08:49 GMT</pubDate>
            <atom:updated>2017-10-26T23:08:48.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCY1lxhwbYmlyGAfrljfHA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/LbjcsNneKCY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jesse Vermeulen</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>TLDR- below is the code snippet for hosting a React Application and a Rest API on the same Express server.</p><pre>const express = require(&#39;express&#39;);<br>const app = express();</pre><pre>const bodyParser = require(&#39;body-parser&#39;);<br>const path = require(&#39;path&#39;);</pre><pre>app.use(express.static(path.join(__dirname, &#39;build&#39;)));</pre><pre>app.use(bodyParser.json());</pre><pre>app.get(&#39;/api/getRequest&#39;, (req, res) =&gt; {<br> //API logic<br> });<br>});</pre><pre>app.post(&#39;/api/postRequest&#39;, (req, res) =&gt; {<br> //API logic<br> });<br>});</pre><pre>app.get(&#39;*&#39;, (req,res) =&gt; {<br> res.sendFile(path.join(__dirname, &#39;build/index.html&#39;));<br>});</pre><pre>const port = process.env.PORT || 3000;</pre><pre>app.listen(port, () =&gt; {<br> console.log(&#39;Listening on port&#39;, port);<br>});</pre><h4>Serving up React</h4><p>React applications need to be rendered on a server, and most React applications require an API. Express makes it easy to host both the React application and the application API.</p><p>First let’s assume that you have a React build (you can do this with the ‘npm run build’ command in create-react-app).</p><p>Next we will create our server script- before we get started be sure to install Express.</p><pre>npm install express --save</pre><p>To start off let’s import all of the tools we will need.</p><pre>const express = require(&#39;express&#39;);       //Express to run our app<br>const app = express();                    //Initiate the app</pre><pre>const bodyParser = require(&#39;body-parser&#39;);//Parse JSON requests<br>const path = require(&#39;path&#39;);             //Navigate to build folder</pre><p>Now that we have our tools in place, let’s render the React application. The app.use() function along with path will reference the React build so it can be served by Express.</p><pre>app.use(express.static(path.join(__dirname, &#39;build&#39;)));</pre><p>Next let’s tell Express to send our React application to the client in the case that a request doesn’t match our specified API.</p><pre>app.get(&#39;*&#39;, (req,res) =&gt; {<br> res.sendFile(path.join(__dirname, &#39;build/index.html&#39;));<br>});</pre><p>The finish off the React app, let’s initiate the Express server and have it start listening for requests.</p><pre>const port = process.env.PORT || 3000;</pre><pre>app.listen(port, () =&gt; {<br> console.log(&#39;Listening on port&#39;, port);<br>});</pre><p>Now if you navigate to localhost:3000 you should see your react application.</p><p>We are only half way there- next let’s add a REST API to our Express app.</p><h4>Adding the API</h4><p>So far we’ve pulled our React build into express and served it up. Most React applications require an API to access databases and protect application functionality. Sometimes it’s best to keep your application and your API on the same server. Express does a lot of the heavy lifting here for us. Let’s get started by adding a get request to our API.</p><pre>//API get request before serving React<br>app.get(&#39;/api/getRequest&#39;, (req, res) =&gt; {<br> //API logic<br> });<br>});</pre><pre>//Serving React<br>app.get(&#39;*&#39;, (req,res) =&gt; {<br> res.sendFile(path.join(__dirname, &#39;build/index.html&#39;));<br>});</pre><p>Here we’ve told our application to give a JSON response when a get request is received at the URL api/getRequest. Notice how we listed this API function before we listed the React build function. Express will run top to bottom when receiving a request and we want any request to be matched with the API requests before we serve up React.</p><p>Next let’s do the same with a post request.</p><pre>//API get request before serving React<br>app.get(&#39;/api/getRequest&#39;, (req, res) =&gt; {<br> //API logic<br> });<br>});</pre><pre>//API post request also before serving React<br>app.post(&#39;/api/postRequest&#39;, (req, res) =&gt; {<br> //API logic<br> });<br>});</pre><pre>//Serving React<br>app.get(&#39;*&#39;, (req,res) =&gt; {<br> res.sendFile(path.join(__dirname, &#39;build/index.html&#39;));<br>});</pre><p>Once again we place the post request before the React build to ensure that the post API request is checked before defaulting to serving the React build.</p><p>Now that we have our API functions up, we can now ping our REST API from our React application. The final code snippet is found at the beginning of this post.</p><p>Thanks for reading!</p><p>If you’d like to hear more then subscribe to the weekly newsletter.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28f7ba5a4cc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/hosting-react-and-a-rest-api-with-express-28f7ba5a4cc4">Hosting React and a REST API with Express</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using create-react-app]]></title>
            <link>https://medium.com/byte-sized-react/using-create-react-app-a71aa0447a58?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/a71aa0447a58</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Thu, 12 Oct 2017 18:24:12 GMT</pubDate>
            <atom:updated>2017-10-12T18:24:11.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wkHbbtIeZaINzdFjCRfHQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/-7ip4yX5P6Q?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jamie Street</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The create-react-app build tool does a ton of heavy lifting when developing and launching a React app.</p><p>How much heavy lifting exactly?</p><h3>What goes into developing and running a React app</h3><p>Building a deployable React app isn’t just a walk in the park Kazansky. Building a React app involves compiling various files, rendering the app on a development server, producing build files, and troubleshooting. Fortunately the create-react-app package handles all of this beautifully.</p><h4>The Compile</h4><p>The first step in producing a React app is compiling all of the various files into one bundle of build files. This includes compiling CSS files, JS modules and Files, JSX, and new JS syntax (ES6 and ES7 for example) all together into one build. The typical build includes an index.html file where your root div element will be defined that will import your CSS and JS files. Next your build will also include a CSS main file which will include all of your compiled CSS. And finally your build will include the main JS file which will include all of your imported NPM packages and modular JS files.</p><p>The create-react-app package largely handles this using Babel and Webpack. Babel is a JS library that converts JSX and the likes of ES6 and ES7 into plain JavaScript, while Webpack is a web bundler that takes all of your files and brings them together into one build.</p><p>Fortunately for us, create-react-app already comes with Babel and Webpack both installed and configured. Installing and configured Babel and Webpack can be a chore all on their own (trust me… Google ‘how to configure Babel and Webpack’- it’s a little more involved than you would think).</p><h4>The Troubleshoot</h4><p>Next is troubleshooting- it’s nice to have some warning beforehand if some code won’t compile or if a function decides to go AWOL. Create-React-App comes pre-loaded and pre-configured with ES lint- a fancy tool for finding compile errors before running your code. It will help you find things like undefined variables, missing syntax, and even identity unused variables. Those errors will be delivered right to your command line and even in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yvco4G0pVDv_RjXvUo59g.png" /><figcaption>Failed compile in the command line</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXQ0FaHbbT6Lv4XG76rsGQ.png" /><figcaption>Failed compile in the browser</figcaption></figure><h4>The Development Server</h4><p>Oh boy- now how can we see our app? It’s not as easy as launching index.html in Chrome- you have to have a server running to serve up your index.html file for React to work. You can go all grass roots and use SimpleHTTPServer in Python, but fortunately Create-React-App has a development server built in that will launch and run your app while in development.</p><p>One of the best things about create-react-app is that you can be constantly updating your application and the create-react-app will automatically load the new changes every time you save. This is called ‘hot reloading’. Basically it allows you to see the results of your new changes without stopping and restarting your development server.</p><h4>The Build</h4><p>The last step is creating the build for the application. This is the process of taking all of the files used in your application and compiling them into three main files (your HTML, CSS, and JS files).</p><p>The build files are optimized for running in the browser, and will be the actual assets that you use when deploying your application. When you are ready, create-react-app makes it very easy to generate a build with one simple command.</p><h3>How to use it</h3><p>Hopefully by now you see the benefits of create-react-app, and now you want to get your hands on this luxurious tool. Let’s walk through how to use creat-react-app.</p><h4>Install</h4><p>The create-react-app package installs just like any other NPM package. Run the following command to install create-react-app globally via NPM.</p><pre>npm install -g create-react-app</pre><h4>Create App</h4><p>Now let’s use create-react-app. You will run the ‘create-react-app’ command followed by the name of the app, in this case ‘my-first-react-app’.</p><pre>create-react-app my-first-react-app</pre><p>It may take a few minutes, but once the process is complete you will have a new directory titled with the app name (‘my-first-react-app’ in this case). Move into the directory to access the rest of the create-react-app commands.</p><pre>cd my-first-react-app</pre><h4>Run</h4><p>The create-react-app package will already come pre-loaded with a simple app to help you get started. Run the following command to bundle the development files and launch the development server.</p><pre>npm start</pre><p>This will run the linting prior to launching your app on your local server at port 3000. Open a web browser and navigate to <a href="http://localhost:3000/">http://localhost:3000/</a> to see the app. It should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNLzsfoPkZl1F5IkCK6wtw.png" /><figcaption>The create-react-app default app page</figcaption></figure><h4>Hot Reloading</h4><p>Now here’s one of the best parts about create-react-app: hot reloading. Anytime you save changes to your app the pre-configured webpack will recognize the save, lint your files, bundle your files, re-compile the code, and launch your app (usually within a matter of seconds). All you have to do is save changes to a file in the ‘src’ directory.</p><h4>Build</h4><p>When you are finished developing on your app you can run the build command for create-react-app to build your deployable files. Run the following command to create your build.</p><pre>npm run build</pre><p>After running the build command you will see a ‘build’ folder in your app directory.</p><h4>Serve</h4><p>Now that you have you build up, let’s go ahead and serve up the app using the ‘serve’ npm package. If you don’t have serve installed, go ahead and install it using the following command.</p><pre>npm install -g serve</pre><p>After installing serve, you can run you build from the app root directory with the following command.</p><pre>serve -s build</pre><p>The serve package will serve the files locally and copy the address location to your clipboard. Open up the app by navigating to the address in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*RkKCBgnNUCHTHcgNVk3dSg.png" /></figure><p>Now you are ready to take the world by storm with your create-react-app know-how!</p><p>If you like learning about React, then subscribe to the Byte-sized React weekly newsletter to get articles like this in your email.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a71aa0447a58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/using-create-react-app-a71aa0447a58">Using create-react-app</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to the React Component Lifecycle]]></title>
            <link>https://medium.com/byte-sized-react/a-guide-to-the-react-component-lifecycle-af5b5f681c3f?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/af5b5f681c3f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Sun, 01 Oct 2017 15:10:04 GMT</pubDate>
            <atom:updated>2018-08-28T15:11:52.660Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjEbLFjut-hjcBH_6lknsQ.jpeg" /><figcaption>Thanks to Death to Stock. <a href="https://deathtothestockphoto.com/photo_pack/wild/">https://deathtothestockphoto.com/photo_pack/wild/</a></figcaption></figure><p>React lifecycle methods are sequential beauties.</p><p>React focuses on handling DOM updates in association to changes in mutable data (state) and immutable data (props). Built into React are lifecycle methods which allow you to invoke code blocks through the lifecycle of updating data and rendering the DOM.</p><p>The three major phases of the React component lifecycle are mounting, updating, and unmounting.</p><h3>What is ‘mounting’?</h3><p>Mounting is the term used in React for when a component is initialized and rendered in the DOM. And likewise, unmounting is when a component is removed from the DOM. In between mounting and unmounting we typically have updates to data and to the DOM. React comes out of the box with methods that are executed at each different stage of the component lifecycle.</p><p>Let’s take a look at each phase and its methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hweYX28xJaQ6qhYvUNKmPw.png" /></figure><h3>Mounting</h3><p>React component being created and rendered in the DOM.</p><h4>constructor(props)</h4><p>The constructor is part of ES6 object syntax, so this shouldn’t be too unfamiliar. This is the first block of code that is executed when a component class object is being created. You should always pass props to the constructor method and then call ‘super(props)’ in the constructor as well. The ‘super’ keyword calls the constructor method in the parent class. Calling ‘super(props)’ calls the parent constructor with the child component’s props initializing the React.Component object constructor giving us the many React features we know and love.</p><p>The constructor method is also where we initiate our state, or our mutable component data. The this.state value is set to a Javascript object.</p><p>The constructor is also where you define the class methods and bind them to ‘this’ so that you can access this.state, this.method and so on within those given methods. When the constructor method is called, no mounting has taken place.</p><pre>constructor(props) {<br>  super(props);<br>  <br>  this.state = {<br>    myData: data,<br>    moreData: thisData<br>  };</pre><pre>  this.componentMethod = this.componentMethod.bind(this);<br>}</pre><h4>componentWillMount()</h4><p>Now that the component has been initialized with the constructor method, it’s time to prep before rendering the component. The componentWillMount method is called after the constructor but before the component is rendered. The componentWillMount method is already baked into React.Component, so no need to define and bind the method (as it is with all of the lifecycle methods).</p><p>This is a great time to make requests for data from external APIs. However, one thing to keep in mind is that React handles requests asynchronously. Meaning that your code will be executed, but React will not wait for the response before moving onto the rest of the lifecycle methods.</p><h4>render()</h4><p>The almighty render- this method returns the React elements that will be rendered in the DOM. JSX allows for writing HTML like code within the render method that is converted to nested createReactElement functions that return the React elements to be rendered. The render function is only called once during the mounting process, and is subsequently called whenever updates are made to the component’s state or props.</p><h4>componentDidMount</h4><p>The componentDidMount is the last mounting method and is called after the component has initially been created and rendered to the DOM. This is a perfect time for making any changes or requests that require DOM nodes. For example if you are using D3 for visualizations, you can make the D3 adjustments after the the original container element has been rendered to the DOM.</p><h3>Updating</h3><h4>componentWillReceiveProps(nextProps)</h4><p>The componentWillReceiveProps method is called right before props are actually updated. This method has access to what the next props will be via ‘nextProps’. This provides a unique point to compare the current props values to the new props values. If you need to update state to match the new props, this is a great place to do it.</p><p>Notice how this method only refers to props, not state. A ‘setState’ call that updates state, and not props, will not invoke this method. This method is typically called when the parent component state is being passed down as props and then the parent state is updated thus updating the component’s props.</p><h4>shouldComponentUpdate</h4><p>The shouldComponentUpdate method is unique in that it is the only method that determines if other lifecycle methods will be called. This method must return a boolean value (the default is true) which will determine if componentWillUpdate, render, and componentDidUpdate will be invoked. If shouldComponentUpdate returns True then the remaining update methods will be invoked. This is the default behavior. However, if shouldComponentUpdate returns false, then the rest of the update methods will not be called.</p><p>The shouldComponentUpdate method has access to the new props and state via the ‘nextProps’ and ‘nextState’ parameters.</p><h4>componentWillUpdate(nextProps, nextState)</h4><p>The componentWillUpdate method is called right before the re-render after updating props or state. This method has access to the ‘nextProps’ and ‘nextState’ parameters which makes it great for making changes in preparation for a re-render.</p><p>React likes to keep you from creating unending chains of ‘setState’ cause by one update, so you can’t call setState in the componentWillUpdate method. If you do need to setState based on a props change, then you will want to make that change in the componentWillRecieveProps method.</p><h4>render()</h4><p>We only see changes to the DOM when render is called on a component. One of the most common methods for calling render is using this.setState(). The this.setState() method accepts a JSON object that update the mutable state and then calls a re-render.</p><p>Render on updates only occurs if shouldComponentUpdate returns true, and if props or state are changed. There is the option to call a force update in React, but try to avoid that at all cost.</p><h4>componentDidUpdate(prevProps, prevState)</h4><p>The componentDidUpdate method is invoked right after the DOM has been updated. This method has access to the previous props and state via ‘prevProps’ and ‘prevState’ and is only called if shouldComponentUpdate returns true.</p><p>This is a great time to operate on the DOM if an update is needed via a different library such as D3, or to make network requests to sync back-end databases with state changes.</p><h3>Unmounting</h3><p>Unmounting occurs when a React component is removed from the DOM.</p><h4>componentWillUnmount()</h4><p>The componentWillUmount method is called every time after a React component is removed from the DOM. This is a great time to do some data clean up and close open socket connections. For example, if you have a real-time messaging component that initiated a real-time database connection in componentWilMount you will want to close that connection in comonentWillUnmount. Otherwise you will stack up several open connections that will slow down your page.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af5b5f681c3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/a-guide-to-the-react-component-lifecycle-af5b5f681c3f">A Guide to the React Component Lifecycle</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chuck Norris Fact Generator with Axios and React]]></title>
            <link>https://medium.com/byte-sized-react/chuck-norris-fact-generator-with-axios-and-react-84cce8fc3b0a?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/84cce8fc3b0a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Tue, 19 Sep 2017 06:06:26 GMT</pubDate>
            <atom:updated>2017-09-19T06:06:32.031Z</atom:updated>
            <content:encoded><![CDATA[<p>Every human deserves a daily dose of Chuck Norris facts- we’ll use Axios and the <a href="https://api.chucknorris.io/">Chuck Norris Facts API</a> by <a href="https://twitter.com/MatChilling">Mathias Schilling</a> to built a Chuck Norris Fact Generator.</p><p>Axios makes it easy to fetch data- let’s put this together in CodePen using React and Bootstrap. If you don’t know how to configure CodePen for React, check out <a href="https://medium.com/byte-sized-react/creating-a-simple-react-component-721589064400">this story</a>.</p><p>Once you have your pen up, add this to your JS file:</p><pre>class App extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      fact: &#39;Chuck Norris can text using his walkie talkie and without batteries.&#39;<br>    };<br>  }<br>  <br>  render() {<br>    return(<br>      &lt;div className=&quot;container text-center&quot;&gt;<br>        &lt;h1&gt;Chuck Norris Facts&lt;/h1&gt;<br>        &lt;h3&gt;{&#39;&quot;&#39; + this.state.fact + &#39;&quot;&#39;}&lt;/h3&gt;<br>        &lt;button type=&quot;button&quot; <br>          className=&quot;btn btn-primary&quot;&gt;<br>          More Chuck Facts!<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;App /&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>And add this touch in your CSS for spacing:</p><pre>.container {<br>  margin-top: 32px;<br>}</pre><p>Your CodePen should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5xaHKFL6181X0WCYnWzag.png" /><figcaption><a href="https://codepen.io/trey-davis/pen/qPOgmX">https://codepen.io/trey-davis/pen/qPOgmX</a></figcaption></figure><p>Nothing special here, just a quick layout for rendering our Chuck Facts. So far we have a static page, let’s make it dynamic by pulling random Chuck Norris facts from the <a href="https://api.chucknorris.io/">Chuck Norris API</a> (thanks to <a href="https://twitter.com/MatChilling">@MatChilling</a> for this API).</p><p>We are going to use Axios to pull the data from the Chuck Norris API. Axios makes it easy to send get and post requests. You can dive more into Axios <a href="https://medium.com/codingthesmartway-com-blog/getting-started-with-axios-166cb0035237">here</a>.</p><p>Pull Axios into your CodePen by adding the content delivery network link to the JS settings page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*w_j8YRMnu6CYFY0jnvNeAg.png" /></figure><p>Now that we have Axios being pulled into our pen, let’s declare the our getFact function that will fetch random facts from the Chuck Norris API. Add the following to your constructor:</p><pre>this.getFact = this.getFact.bind(this);</pre><p>Now let’s add our logic to request the Chuck Norris fact using Axios.</p><pre>  getFact() {<br>    axios.get(&#39;<a href="https://api.chucknorris.io/jokes/random&#39;">https://api.chucknorris.io/jokes/random&#39;</a>)<br>      .then(response =&gt; {<br>      this.setState({fact: response.data.value});<br>    }).catch(error =&gt; {<br>      console.log(error);<br>    });<br>  }</pre><p>To make a get request with Axios, we use ‘axios.get’ and then pass the url for the request. Axios is promise-based, so we will respond with the data/error using then/catch.</p><p>In our ‘then’ function, we will take the response and access the API data using response.data. According to the Chuck Norris API, we access the random fact via the value attribute, so we will use response.data.value.</p><p>After accessing the random fact we will call setState to update the ‘fact’ state to reflect the new random fact.</p><p>Let’s tie this up by passing the ‘getFact’ method to our button using the ‘onClick’ React event. Add this to the button:</p><pre>onClick={this.getFact}</pre><p>Now your code should look like this:</p><pre>class App extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      fact: &#39;Chuck Norris can text using his walkie talkie and without batteries.&#39;<br>    };<br>    <br>    this.getFact = this.getFact.bind(this);<br>  }<br>  <br>  getFact() {<br>    axios.get(&#39;<a href="https://api.chucknorris.io/jokes/random&#39;">https://api.chucknorris.io/jokes/random&#39;</a>)<br>      .then(response =&gt; {<br>      this.setState({fact: response.data.value});<br>    }).catch(error =&gt; {<br>      console.log(error);<br>    });<br>  }<br>  <br>  render() {<br>    return(<br>      &lt;div className=&quot;container text-center&quot;&gt;<br>        &lt;h1&gt;Chuck Norris Facts&lt;/h1&gt;<br>        &lt;h3&gt;{&#39;&quot;&#39; + this.state.fact + &#39;&quot;&#39;}&lt;/h3&gt;<br>        &lt;button type=&quot;button&quot; <br>          className=&quot;btn btn-primary&quot;<br>          onClick={this.getFact}&gt;<br>          More Chuck Facts!<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>And now you can request new Chuck Norris facts by selecting the button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deZESsy_gW0G-N368-rgfg.gif" /></figure><p>You can check out the CodePen <a href="https://codepen.io/trey-davis/pen/qPOgmX">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fembed%2Fpreview%2FqPOgmX%3Fheight%3D600%26slug-hash%3DqPOgmX%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fpen%2FqPOgmX&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1166633.qPOgmX.small.27a852b9-521d-4d76-b847-7db413f65b64.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd10cb3c8db7edb36ced7db7aae2e592/href">https://medium.com/media/bd10cb3c8db7edb36ced7db7aae2e592/href</a></iframe><p>Let’s break down the flow for requesting a new random fact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iqvdfUvOBFLyvNYRtAGNA.png" /></figure><p>So far we’ve been building React apps using CodePen- next we’ll build and run a React app using the create-react-app NPM package.</p><p>If you liked that post subscribe to Byte-sized React’s weekly newsletter to receive weekly React tips and tutorials right in your inbox.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84cce8fc3b0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/chuck-norris-fact-generator-with-axios-and-react-84cce8fc3b0a">Chuck Norris Fact Generator with Axios and React</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlled Forms in React]]></title>
            <link>https://medium.com/byte-sized-react/controlled-forms-in-react-68e59362a119?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/68e59362a119</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Thu, 14 Sep 2017 23:55:44 GMT</pubDate>
            <atom:updated>2017-09-14T23:55:44.027Z</atom:updated>
            <content:encoded><![CDATA[<p>React makes it easy to manipulate data using forms.</p><p>Form input values can be set to state values and then updated via React events. Defining a form’s input value via state is considered a controlled component.</p><p>For controlled inputs you will need a corresponding state and then a class method to update that state with changes.</p><p>Let’s walk through a quick example with CodePen. If you don’t know how to set up CodePen with React, you can check out <a href="https://medium.com/byte-sized-react/creating-a-simple-react-component-721589064400">this story</a>.</p><p>Let’s also add Boostrap 4 to our CodePen so our forms aren’t so plain.</p><p>Add this to your JS file:</p><pre>class App extends React.Component {<br>  constructor(props) {<br>    super(props);<br>  }<br>  <br>  render() {<br>    return (<br>      &lt;div className=&quot;form-group container&quot;&gt;<br>        &lt;label&gt;Controlled Form Input&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; <br>          className=&quot;form-control&quot; <br>          aria-describedby=&quot;emailHelp&quot; <br>          placeholder=&quot;Update input here&quot; /&gt;<br>        &lt;large className=&quot;form-text text-muted&quot;&gt;<br>          Form Output<br>        &lt;/large&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;App /&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Now your CodePen should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Lrpq8ohSE0zzZNe7ETNhQ.png" /></figure><p>Right now our form input is not controlled- meaning that the value of the form input is not determined by the state. Let’s add a state value for the form making it a controlled form.</p><p>Declare the state value in your constructor.</p><pre>constructor(props) {<br>    super(props);<br>    this.state({input: &#39;&#39;});<br>  }</pre><p>Then let’s pass the state input value down to the value of the email form and as the value of our output text.</p><pre>&lt;input type=&quot;text&quot; <br>   className=&quot;form-control&quot; <br>   aria-describedby=&quot;emailHelp&quot; <br>   placeholder=&quot;Update input here&quot; <br>   value={this.state.input}/&gt;<br> &lt;large className=&quot;form-text text-muted&quot;&gt;<br>   {this.state.input}<br> &lt;/large&gt;</pre><p>Now notice how the value of the form reflects the state, but the form value doesn’t update. That’s because we don’t have a method that will update state. Let’s add a method to update state, and pass it down using the onChange event handler.</p><p>Add the method to your constructor.</p><pre>constructor(props) {<br>  super(props);<br>  this.state = ({input: &#39;&#39;});<br>  this.formUpdate = this.formUpdate.bind(this);<br>}</pre><p>Now define the formUpdate method.</p><pre>formUpdate(event) {<br>  this.setState({input: event.target.value});<br>}</pre><p>The formUpdate function needs to be called whenever a change is made to the form input. Use the onChange react event to trigger the formUpdate method.</p><pre>&lt;input type=&quot;text&quot; <br>  className=&quot;form-control&quot; <br>  aria-describedby=&quot;emailHelp&quot; <br>  placeholder=&quot;Update input here&quot; <br>  value={this.state.input}<br>  onChange={this.formUpdate}/&gt;</pre><p>Every time a change happens to the form the formUpdate method will be called with the event object. From the event object we can pull the form value using event.target.value.</p><p>Now your form should be functioning like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*YdlbXbZkO34mnkS4-bcUpA.gif" /></figure><p>Let’s take a look at what is going on here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPa4yO4rACiK244hdyRYXw.png" /></figure><p>Here’s the functioning CodePen:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fembed%2Fpreview%2FJrdYZP%3Fheight%3D600%26slug-hash%3DJrdYZP%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fpen%2FJrdYZP&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1166633.JrdYZP.small.94e3df00-da74-47cb-8e99-2a3090724df5.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/61702b18d571e4443b4b1aa3427597e1/href">https://medium.com/media/61702b18d571e4443b4b1aa3427597e1/href</a></iframe><p>In our next story we’ll pull some data from an API using Axios.</p><p>If you liked that story subscribe to Byte-sized React’s weekly newsletter to receive weekly React tips and tutorials right in your inbox.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68e59362a119" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/controlled-forms-in-react-68e59362a119">Controlled Forms in React</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling State and Class Components in React]]></title>
            <link>https://medium.com/byte-sized-react/handling-state-and-class-components-in-react-772e542d8fd6?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/772e542d8fd6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Tue, 12 Sep 2017 23:20:21 GMT</pubDate>
            <atom:updated>2017-09-12T23:20:19.495Z</atom:updated>
            <content:encoded><![CDATA[<p>Data changes- that’s one of the beautiful thing about web apps. Changing data and then presenting a visual representation of that change. React handles mutable, component-based data called state. Functional React components don’t handle state, so you’ll need to upgrade to React class components. This is what a React class component looks like:</p><pre>class App extends React.Component {</pre><pre>  constructor(props){<br>    super(props);<br>    this.state = {message: &#39;Hello world!&#39;};<br>  }</pre><pre>  render(){<br>    &lt;h1&gt;{this.state.message}&lt;/h1&gt;<br>  }<br>}</pre><p>Let’s break down what is going on here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iVRKUU5QrW7B0erzzVyEg.png" /></figure><p>Notice how the class component uses the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">class structure</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super">super keyword</a> to initiate the component.</p><p>Let’s walk through a simple example in CodePen of creating a class component in React, declaring state, and updating state.</p><p>Start up a pen with React, ReactDOM, and Bootstrap styling in CodePen. If you don’t know how to set up React in CodePen, <a href="https://medium.com/byte-sized-react/creating-a-simple-react-component-721589064400">check out this story</a>.</p><p>Also <a href="https://medium.com/byte-sized-react/simple-react-styling-233cef4eaba8">add Bootstrap 4 for styling</a>.</p><p>We are going to build a simple counter where a user can increase or decrease the count using plus (+) and minus (-) buttons. Let’s lay out the structure of our app using a class component.</p><pre>class App extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {count: 0};<br>  };<br>  <br>  render(){<br>    return (<br>      &lt;div className=&quot;container text-center class-width&quot;&gt;<br>        &lt;div className=&quot;card&quot;&gt;<br>          &lt;div className=&quot;card-block&quot;&gt;<br>            &lt;h1 className=&quot;card-title&quot;&gt;{this.state.count}&lt;/h1&gt;<br>            &lt;div className=&quot;btn-group btn-group-lg&quot; <br>              role=&quot;group&quot; aria-label=&quot;Basic example&quot;&gt;<br>              &lt;button type=&quot;button&quot; <br>                className=&quot;btn btn-secondary&quot;&gt; - &lt;/button&gt;<br>              &lt;button type=&quot;button&quot; <br>                className=&quot;btn btn-secondary&quot;&gt; + &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;App /&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Add the following to your CSS file to help position the counter:</p><pre>.class-width {<br>  max-width: 150px;<br>  margin-top: 100px;<br>}</pre><p>Your CodePen should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDeRXmytnYFty036vRhIBA.png" /><figcaption><a href="https://codepen.io/trey-davis/pen/MEgXLz">https://codepen.io/trey-davis/pen/MEgXLz</a></figcaption></figure><p>We are using state to render the count, but there isn’t a way to update the count. React has built-in event listeners that will trigger functions when activated. Let’s use the ‘onClick’ event listener on our buttons to add and subtract the values to our counter, but first we need to declare the functions in our class constructor.</p><pre>  constructor(props) {<br>    super(props);<br>    this.state = {count: 0};<br>    <br>    this.increment = this.increment.bind(this);<br>    this.decrement = this.decrement.bind(this);<br>  };</pre><p>Next let’s add the actually functions- you will declare these as functions in your App class:</p><pre>  increment() {<br>    let count = this.state.count;<br>    count++;<br>    this.setState({count: count});<br>  }<br>  <br>  decrement() {<br>    let count = this.state.count;<br>    count--;<br>    this.setState({count: count});<br>  }</pre><p>The setState function is the React method that actually updates the state data. When setState is called a re-render is pushed and the DOM is automatically updated.</p><p>Now that we have our functions put together, let’s add our ‘onClick’ event listener to our button components to trigger the increment and decrement functions.</p><pre>&lt;button type=&quot;button&quot; className=&quot;btn btn-secondary&quot;<br>   onClick={this.decrement}&gt; - &lt;/button&gt;</pre><pre>&lt;button type=&quot;button&quot; className=&quot;btn btn-secondary&quot;<br>   onClick={this.increment}&gt; + &lt;/button&gt;</pre><p>When you are done you JavaScript file should look like this:</p><pre>class App extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      count: 0<br>    }<br>    <br>    this.increment = this.increment.bind(this);<br>    this.decrement = this.decrement.bind(this);<br>  };<br>  <br>  increment() {<br>    let count = this.state.count<br>    count++;<br>    this.setState({count});<br>  }<br>  <br>  decrement() {<br>    let count = this.state.count<br>    count--;<br>    this.setState({count});<br>  }<br>  <br>  render(){<br>    return (<br>      &lt;div className=&quot;container text-center class-width&quot;&gt;<br>        &lt;div className=&quot;card&quot;&gt;<br>          &lt;div className=&quot;card-block&quot;&gt;<br>            &lt;h1 className=&quot;card-title&quot;&gt;{this.state.count}&lt;/h1&gt;<br>            &lt;div className=&quot;btn-group btn-group-lg&quot; <br>              role=&quot;group&quot; aria-label=&quot;Basic example&quot;&gt;<br>              &lt;button type=&quot;button&quot; className=&quot;btn btn-secondary&quot;<br>                onClick={this.decrement}&gt; - &lt;/button&gt;<br>              &lt;button type=&quot;button&quot; className=&quot;btn btn-secondary&quot;<br>                onClick={this.increment}&gt; + &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;App /&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>And now your counter should be fully functional- you can increase and decrease the count every time to click the plus (+) or minus (-) buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*-mIwlC9lbgE2e4VW2dFJ5A.gif" /></figure><p>Let’s take a quick walk through what is happening every time you click the increment button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RsjAGpn9io53ER7B_d23g.png" /></figure><p>Now we’ve constructed a class component and manipulated component data. Next we’ll look at how we manage data in forms.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772e542d8fd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/handling-state-and-class-components-in-react-772e542d8fd6">Handling State and Class Components in React</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Styling with Bootstrap Classes in React]]></title>
            <link>https://medium.com/byte-sized-react/simple-react-styling-233cef4eaba8?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/233cef4eaba8</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Mon, 11 Sep 2017 21:32:34 GMT</pubDate>
            <atom:updated>2017-09-12T02:36:58.357Z</atom:updated>
            <content:encoded><![CDATA[<p>So far our components have been pretty plain- let’s change that up by adding a CSS class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNWHYUkUn_qe9b91GEc_8Q.png" /></figure><p>In HTML we would include a ‘class’ attribute- however, ‘class’ is a reserved term in JavaScript, so using ‘class’ in JSX won’t work. Fortunately JSX will compile ‘className’ into ‘class’, so we’ll use ‘className’ to add some styling.</p><pre>const Component = props =&gt; {<br>  return (<br>    &lt;h1 className={&#39;cssClass&#39;}&gt;Hello world!&lt;/h1&gt;<br>  );<br>}</pre><p>This will render HTML elements with the defined CSS class and the browser will apply the matching class styles defined in your CSS files.</p><p>Let’s walk through a quick CodePen example and add some Bootstrap styling to a quote list.</p><p>If you don’t know you to set up CodePen for React, check out <a href="https://medium.com/@treyadavis/creating-a-simple-react-component-721589064400">this story</a>.</p><p>In addition to setting up CodePen for React, let’s add Bootstrap as well. You do this by selecting the gear icon for your pen, selecting CSS, and selecting Bootstrap from the quick add menu.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FhZzqpeLKwLSM0%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FhZzqpeLKwLSM0&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FhZzqpeLKwLSM0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="331" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b91b34be93ae8de00d839dd5ee77796/href">https://medium.com/media/6b91b34be93ae8de00d839dd5ee77796/href</a></iframe><p>Now let’s add our quote data and components to the JavaScript file.</p><pre>const quotes = [<br>  {text: &#39;Whatever the mind of man can conceive and believe, it can achieve.&#39;,<br>  author: &#39;Napoleon Hill&#39;},<br>  {text: &#39;Strive not to be a success, but rather to be of value.&#39;,<br>  author: &#39;Albert Einstein&#39;},<br>  {text: &#39;I attribute my success to this: I never gave or took any excuse.&#39;,<br>  author: &#39;Florence Nightingale&#39;},<br>  {text: &#39;You miss 100% of the shots you don’t take.&#39;,<br>  author: &#39;Wayne Gretzky&#39;}<br>];</pre><pre>const Heading = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Famous Quotes&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>const Quote = props =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        &lt;h4&gt;{props.quote.text}&lt;/h4&gt;<br>        &lt;h6&gt;{props.quote.author}&lt;/h6&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>const App = props =&gt; {<br>  const quotes = props.quotes.map((quote) =&gt; {<br>    return (<br>      &lt;Quote quote={quote} /&gt;<br>    )<br>  });<br>  return (<br>    &lt;div&gt;<br>      &lt;Heading /&gt;<br>      &lt;div&gt;<br>        {quotes}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>And then finish off with a render:</p><pre>ReactDOM.render(<br>  &lt;App quotes={quotes} /&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Your CodePen should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUlpz_nwP7tjffbr7V37Hw.png" /></figure><p>It’s pretty plain right now- so let’s pick out some styling. I’m going to use the Card and Jumbotron classes from Bootstrap. You can see their styling here:</p><p><a href="https://v4-alpha.getbootstrap.com/components/card/">Card</a></p><p><a href="https://v4-alpha.getbootstrap.com/components/jumbotron/">Jumbotron</a></p><p>Let’s add the classes using ‘className’.</p><pre>const Heading = () =&gt; {<br>  return (<br>    &lt;div className=&quot;jumbotron&quot;&gt;<br>      &lt;h1 className=&quot;display-3&quot;&gt;Famous Quotes&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>const Quote = props =&gt; {<br>  return (<br>    &lt;div className=&quot;card&quot;&gt;<br>      &lt;div className=&quot;card-block&quot;&gt;<br>        &lt;h4 className=&quot;card-title&quot;&gt;{props.quote.text}&lt;/h4&gt;<br>        &lt;h6 className=&quot;card-subtitle mb-2 text-muted&quot;&gt;{props.quote.author}&lt;/h6&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>const App = props =&gt; {<br>  const quotes = props.quotes.map((quote) =&gt; {<br>    return (<br>      &lt;Quote quote={quote} /&gt;<br>    )<br>  });<br>  return (<br>    &lt;div&gt;<br>      &lt;Heading /&gt;<br>      &lt;div&gt;<br>        {quotes}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Viola! And just like that- our components don’t look so plain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMdICWMMmnhRmS1w0bKA9A.png" /></figure><p>Here’s the CodePen:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fembed%2Fpreview%2FEwYmEJ%3Fheight%3D600%26slug-hash%3DEwYmEJ%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fpen%2FEwYmEJ&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1166633.EwYmEJ.small.4f5cf478-90c9-49cf-a477-c92fa5072fff.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4bf1520c9acb161db55a534735202b1/href">https://medium.com/media/d4bf1520c9acb161db55a534735202b1/href</a></iframe><p>So far we’ve been dealing with data that is immutable via props. Next we’ll learn about state and manipulating data in React.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=233cef4eaba8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/simple-react-styling-233cef4eaba8">Styling with Bootstrap Classes in React</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lists and Arrays in React]]></title>
            <link>https://medium.com/byte-sized-react/component-arrays-in-react-a46e775fae7b?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/a46e775fae7b</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Mon, 11 Sep 2017 21:32:24 GMT</pubDate>
            <atom:updated>2017-09-12T02:35:30.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Often you’ll have a data collection that you want to iterate over and render React components for each item in the array.</p><p>We can do this by creating an array of React elements. We can simply do this by utilizing the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> function on adata array. By returning JSX in our map function, Babel will convert the JSX to React elements.</p><pre>const reactElementsArray = dataArray.map((data) =&gt; {<br>  return (<br>    &lt;p&gt;{data}&lt;/p&gt;<br>  );<br>});</pre><p>We then include the React element array as an expression in JSX to render the array:</p><pre>const reactComponent = props =&gt; {<br>  return(<br>    &lt;div&gt;{reactElementsArray}&lt;/div&gt;  <br>  );<br>};</pre><p>Take a look at this process visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o70ebzCQfJCoeiqOMzYmSA.png" /></figure><p>Now let’s walk through and example in CodePen- if you don’t know how to set up CodePen for React, you can check out <a href="https://medium.com/@treyadavis/creating-a-simple-react-component-721589064400">this story</a>.</p><p>We are going to make a list of famous quotes- let’s start by adding our quote data to the JS file:</p><pre>const quotes = [<br>  {text: &#39;Whatever the mind of man can conceive and believe, it can achieve.&#39;,<br>  author: &#39;Napoleon Hill&#39;},<br>  {text: &#39;Strive not to be a success, but rather to be of value.&#39;,<br>  author: &#39;Albert Einstein&#39;},<br>  {text: &#39;I attribute my success to this: I never gave or took any excuse.&#39;,<br>  author: &#39;Florence Nightingale&#39;},<br>  {text: &#39;You miss 100% of the shots you don’t take.&#39;,<br>  author: &#39;Wayne Gretzky&#39;}<br>];</pre><p>Now let’s add our quote component which will render the quote text and the quote author:</p><pre>const Quote = props =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h4&gt;{props.text}&lt;/h4&gt;<br>      &lt;p&gt;{props.author}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>Quote.propTypes = {<br>  text: React.PropTypes.string,<br>  author: React.PropTypes.string<br>}</pre><p>Notice how we will be accessing the quote and its author via the component’s props.</p><p>Next let’s add our app component that will render our quotes:</p><pre>const App = props =&gt; {<br>  const quoteArray = props.quotes.map((quote) =&gt; {<br>    return (<br>      &lt;Quote text={quote.text} author={quote.author} /&gt;<br>    );<br>  });<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Famous Quotes&lt;/h2&gt;<br>      {quoteArray}<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>App.propTypes = {<br>  quotes: React.PropTypes.array<br>}</pre><p>Notice how we used the map function to generate our React element array and then used the curly braces to insert the quoteArray as a JavaScript expression in the App component. This will return all of the Quote components in our quoteArray.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWQ7v2N27v-I6Ea8oZyHaw.png" /></figure><p>Now render the App component:</p><pre>ReactDOM.render(<br>  &lt;App quotes={quotes} /&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Now your CodePen should look like this (be sure to include the root div in the HTML file):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiNmPJb9PjpMbK9KqgBHMA.png" /><figcaption><a href="https://codepen.io/trey-davis/pen/WEVwQX">https://codepen.io/trey-davis/pen/WEVwQX</a></figcaption></figure><p>Here is the CodePen:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fembed%2Fpreview%2FWEVwQX%3Fheight%3D600%26slug-hash%3DWEVwQX%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fpen%2FWEVwQX&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1166633.WEVwQX.small.9728e4a6-3290-42f5-93cd-0a5064bcf4ed.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/48ca489b54db0950cc9980827deecf2f/href">https://medium.com/media/48ca489b54db0950cc9980827deecf2f/href</a></iframe><p>So far our React components have been looking rather plain- <a href="https://medium.com/@treyadavis/simple-react-styling-233cef4eaba8">next we’ll take a look at applying some simple styling to jazz things up</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a46e775fae7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/component-arrays-in-react-a46e775fae7b">Lists and Arrays in React</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Data with Props in React]]></title>
            <link>https://medium.com/byte-sized-react/handling-data-with-props-in-react-900fdc44a8c?source=rss----12ef1ca9db6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/900fdc44a8c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Trey Alexander Davis]]></dc:creator>
            <pubDate>Mon, 11 Sep 2017 21:32:13 GMT</pubDate>
            <atom:updated>2017-09-12T02:34:01.721Z</atom:updated>
            <content:encoded><![CDATA[<p>Props to you my friend for making it this far.</p><p>So far our components have been static- let’s change that by passing down some data to our components.</p><p>Passing and accessing data in react components is fairly straight forward. Using JSX we pass data to a component as an attribute:</p><pre>&lt;MyComponent someAttribute={data.value} /&gt;</pre><p>In JSX the curly braces indicate a JavaScript expression which must return a value. The passed data is accessed via props in the defined component:</p><pre>const MyComponent = props =&gt; {<br>  &lt;p&gt;{props.someAttribute}&lt;/p&gt;<br>};</pre><p>Now let’s walk through an example in CodePen (if you don’t have a free CodePen account or don’t know how to set up CodePen for React, check out <a href="https://medium.com/@treyadavis/creating-a-simple-react-component-721589064400">this story</a>)- first lets define some dummy data in our JS file:</p><pre>const blogData = {<br>  title: &#39;My blog title&#39;,<br>  body: &#39;Arcu viverra dolor eros interdum, <br>    quis nonummy accusantium at lorem luctus iaculis.&#39;<br>};</pre><p>Next let’s define our blog components:</p><pre>const Heading = () =&gt; {<br>  return (<br>    &lt;h1&gt;My Blog&lt;/h1&gt;<br>  );<br>};</pre><pre>const Blog = props =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{props.title}&lt;/h2&gt;<br>      &lt;p&gt;{props.body}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Noticed how we used the props object to render the title and body values that will be passed to the Blog component. Props is read-only or immutable, so we don’t have to worry about changing the props values.</p><p>Before we write our App component, we need to protect our component be defining the variable type that will passed down to each prop. We will define this using React.PropTypes. Add the following to your JS file:</p><pre>Blog.propTypes = {<br>  title: React.PropTypes.string,<br>  body: React.PropTypes.string<br>};</pre><p>Here we are defining that the the data passed down to our Blog component will be strings for both title and body. Check out <a href="https://facebook.github.io/react/docs/typechecking-with-proptypes.html">React’s documentation</a> for a list of all propTypes.</p><p>Now let’s put this together in an app component and pass down our data:</p><pre>const App = props =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Heading /&gt;<br>      &lt;Blog title={blogData.title} body={blogData.body} /&gt;<br>      &lt;Blog title={blogData.title} body={blogData.body} /&gt;<br>      &lt;Blog title={blogData.title} body={blogData.body} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Finally, let’s render our app (be sure to add a root div tag to the HTML file ):</p><pre>ReactDOM.render(<br>  &lt;App /&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Your CodePen should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjM1u9uaeVg7w_ZXOda4Bg.png" /><figcaption><a href="https://codepen.io/trey-davis/pen/MvdZGX">https://codepen.io/trey-davis/pen/MvdZGX</a></figcaption></figure><p>Let’s break down what’s going on here- red indicates code explanations, blue indicates data flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDRBsktYbw_aojp9eXi-hg.png" /></figure><p>Here is the CodePen:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fembed%2Fpreview%2FMvdZGX%3Fheight%3D600%26slug-hash%3DMvdZGX%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftrey-davis%2Fpen%2FMvdZGX&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1166633.MvdZGX.small.52ffae68-eb41-42ea-9578-9862087c3b76.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/103ac4cf1112e0902707d5724692b003/href">https://medium.com/media/103ac4cf1112e0902707d5724692b003/href</a></iframe><p>Great- now you are passing data to components like a pro. <a href="https://medium.com/@treyadavis/component-arrays-in-react-a46e775fae7b">Next we’ll take a look at rendering arrays in React so we don’t have to list our Blog component 3 times :)</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F43ef1f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F43ef1f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F43ef1f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href">https://medium.com/media/d7e0c3a1b2da5a88f7e2964d0bf7845c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=900fdc44a8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-react/handling-data-with-props-in-react-900fdc44a8c">Handling Data with Props in React</a> was originally published in <a href="https://medium.com/byte-sized-react">Byte-sized React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>