React JS - React Tutorial for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I wish there were more tutorials for experienced react programmers.. too many easy and effortless tutorials

πŸ‘οΈŽ︎ 11 πŸ‘€οΈŽ︎ u/some_coreano πŸ“…οΈŽ︎ Jul 17 2018 πŸ—«︎ replies

This is really well done πŸ‘Œ

πŸ‘οΈŽ︎ 3 πŸ‘€οΈŽ︎ u/tyler-mcginnis πŸ“…οΈŽ︎ Jul 17 2018 πŸ—«︎ replies

I don’t think virtualized would keep the video players time stamped correctly, so some other data later would be needed. And another neat tutorial idea would be seeing various libraries in heavy rotation (like react-virtualized) rebuilt as a tutorial.

πŸ‘οΈŽ︎ 1 πŸ‘€οΈŽ︎ u/frankandsteinatlaw πŸ“…οΈŽ︎ Jul 17 2018 πŸ—«︎ replies

I've cross-posted this to /r/LearnReactJS. :)

πŸ‘οΈŽ︎ 1 πŸ‘€οΈŽ︎ u/Charles_Stover πŸ“…οΈŽ︎ Jul 17 2018 πŸ—«︎ replies

Very well explained and easy to follow. All the best in your teaching pursuits.

πŸ‘οΈŽ︎ 1 πŸ‘€οΈŽ︎ u/FrozenInferno πŸ“…οΈŽ︎ Aug 15 2018 πŸ—«︎ replies
Captions
[Music] hi my name is mohammad ani and i'm going to be your instructor in this react crash course first i'm gonna give you a quick 3 minute introduction to what react is and why you should learn it and then we're going to jump in and build a react application together this application we're going to build throughout this course may appear simple but actually it exhibits patterns that you see on a shopping cart page so imagine these are the items on a shopping cart we can change their quantity delete them reset the quantity of all items to zero and we also have this number on the navigation bar showing the number of unique items in our imaginary shopping cart so by the end of this crash course you will have a good and in-depth understanding of react fundamentals you'll be able to build reusable components render data handle events and debug your react applications if you enjoyed this tutorial please like it and share it with others are you excited now let's get started you [Music] react is a JavaScript library for building fast and interactive user interfaces it was developed at Facebook in 2011 and currently it's the most popular javascript library for building user interfaces as you can see on Google Trends react is dominating the space of libraries and frameworks for building user interfaces the other two players here are angular and view so if you want to expand your job opportunities as a front-end developer you should have react on your resume at the heart of all react applications are components the component is essentially a piece of the user interface so when building applications with react we build a bunch of independent isolated and reusable components and then compose them to build complex user interfaces every react application has at least one component which we refer to as the root component this component represents the internal application and contains other child components so every react application is essentially a tree of components if you have worked with angular 2 or higher it should sound familiar here is an example let's imagine we want to build an application like Twitter we can split this page into components like navbar profile trends and feet here's a representation of these components in a tree so on the top we have app and below that we have navbar profile trends and feet now feed includes several tweet components each tweet component can include a light component which we can reuse on other pages or even in different applications so as you see each component is a piece of UI we can build these components in isolation and then put them together to build complex UIs in terms of implementation a component is typically implemented as a Java Script class that has some state and a render method the state here is the data that we want to display when the component is rendered and the render method as you can tell is responsible for describing what the UI should look like the output of this render method is a react element which is a simple plain JavaScript object that maps to a Dom element it's not a real Dom element it's just a plain JavaScript object that represents that Dom element in memory so react keeps a lightweight representation of the Dom in memory which were referred to as the virtual Dom unlike the browser or the real Dom this virtual DOM is cheap to create when we change the state of a component we get a new react element react will then compare this element and his children with the previous one it figures out what is changed and then it will update a part of the real Dom to keep it in sync with the virtual Dom so that means when building applications with react unlike vanilla JavaScript or jQuery we no longer have to work with the Dom API in browsers in other words we no longer have to write code and query and manipulate the Dom or attach the event handlers to Dom elements we simply change the state of our components and react will automatically update the Dom to match that state and that's exactly why this library is called react because when the state changes react essentially reacts to the state change and updates the dump one of the questions that I often get is react or angular well both react and angular are similar in terms of their component based architecture however angular is a framework or a complete solution wild react is a library it only takes care of rendering the view and making sure that the view is in sync with the state let's all react does nothing less nothing more for this very reason react has a very small API to learn so when building applications with react we need to use other libraries for things like routing or calling HTTP services and so on but this is not necessarily a bad thing because you get to choose the libraries that you prefer as opposed to being fixed with what angular gives you which often breaks from one version to another so that's all about react next we're going to set up our development environment [Music] you [Music] all right this is where the fun begins the first thing I want you to install is no js' now in this course we're not gonna use note we're only gonna use one of its built-in tools node package manager or NPM to install third-party libraries so if you don't have node on your machine head over to node J s that org and download and install the latest stable version once you do that open up the terminal on Mac or command prompt on Windows and run this command NPM I which is short for install - G which is short for global and here's the package we're going to install create - react - app we're gonna use this package to create a new react app now I want you to install the exact same version I'm gonna use in this course because in the future there might be breaking changes and you might get frustrated if what you see is different from what I'm gonna show you so here at sign version 1.5.2 now if you're on Mac and you haven't configured permissions properly you need to put sudo in the front of this command so sudo with this will run this command under administrative privileges let's enter the password okay beautiful now the next thing you need is a code editor the code editor I'm gonna use in this course is Visual Studio code or vs code chances are you use the same because it's a beautiful lightweight and cross-platform editor if you don't have it we can download it from code that Visual Studio calm so here is BS code we're gonna install two extensions that make it easier to build reactions in vs code so open up the extensions panel on the left and search for simple react snippets here's the extension I'm talking about is developed by Burke Holland and currently there are more than 40,000 downloads very very popular extension so install it and then you will have to reload vs code the other extension we're going to install is prettier so search for prettier prettier code formatter this one is developed by s-pen Peterson and currently there are more than 2.7 million downloads we use this extension to reformat our code now one thing I highly encourage you to do so is to enable formatting unsaved so whenever you save the changes this extension will automatically reformat your code to do that you need to go to the settings page now here I'm on Mac I'm not entirely sure how to do this on Windows but that should be pretty straightforward so here on Mac we go to the code menu on the top then preferences and finally settings so here on the right side under user settings I want you to add this setting editor but format unsaved set this to true and finally let me show you what theme I'm using here because that's a question I get quite a lot so on the top go to the code menu preferences color theme this is the theme I'm using so are you or a you me Raj so I leave it up to you to download and install this if you want to next we're going to create our first react app now let's use to create react app package to create a new react application so here in the terminal let's run create react app and give our new application in name let's call it react app now this is going to install react as well as all the third-party libraries we need so it's going to install a lightweight development server web pack from bundling our files Babel or Babel for compiling or JavaScript code as well as a bunch of other tools so when you create an application using create react app you don't have to do any configuration all the configuration is done for you however if you want to customize this configuration for your production environment you can always eject by running npm run eject we'll look at this later in the future so now we have a fully working react app let's go to this new folder react app and run NPM start so this will launch our development server on port 3000 and open up Chrome or our default browser pointing to localhost port 3000 now let's go back to vs code and see what we have in is folder so here we have three folders node modules which is where we have all the third-party libraries as well as react itself we never have to touch this so let's not worry about it we've got this public folder where we have the public assets of our application such as a favorite icon and index dot HTML now if you look at this file this is a very simple template it doesn't really have anything so a bunch of meta tags in the head section as well as links to our manifesto JSON file and favorite icon manifests that JSON includes a bunch of metadata attributes among our application again we don't have to worry about this but if you look further below here in the body section you can see a single div with the ID root this is where our react application is going to appear so this div is the container for our reactor application as you will see shortly now back to our files panel we've got the source folder where we have a basic component that is app component and that component is responsible for rendering this black banner on the top so the output of that component is what you see here let's have a quick look at app that Jas so you can see here we are using es6 classes we have a class called app that extends component which is one of the built-in classes in react now as you can tell as a react developer you need to understand what classes are and how to use them if you're not familiar with these classes I have a comprehensive course called object oriented programming in JavaScript there I cover classes in full detail but to help you get started quickly in the next section I'm gonna give you a quick overview of all the modern JavaScript features that you're going to use frequently in react applications so if you're not familiar with classes or modules don't worry for now we're gonna get to them shortly now look at this class here we have a render method or a render function where we return a mark up like this this is something you probably haven't seen before because we cannot have markup like this in Java scrip note that this is neither a drink nor HTML this is what we call JSX which stands for JavaScript XML so we use this syntax which looks very familiar to us to describe what the UI is going to look like so this markup represents this black banner on the top this is the output of our app component now to make this code work we have to pass this code through babel which is a modern JavaScript compiler so babel will take this JSX syntax and convert it to plain JavaScript code that browsers can understand let me give you a quick demo head over to babel j s dot io / repl or repo here we can type modern JavaScript code and babel will convert that code into code that browsers can understand so here I'm gonna define a constant which is a new es6 feature call it element and set it to a JSX expression so h1 let's say hello world and we close it here again note that here we are not setting element to a string this is JSX so we don't have quotes here right now on the right side look this code is converted to a call to react that create element the first argument to this method is h1 which determines the type of our element and the third argument is the text that we want to put in between is h1 tags so as you can see using JSX to describe what the UI looks like is much easier than writing plain react code like this so in our components will always use JSX and we'll leave it up to Babel to compile that JSX code into calls to react that create element now back to our files panel here we have after CSS which includes all the CSS for our app component you can see this CSS file is imported into our component here we also have a test file that is app that tests rjs in this course we're not gonna look at testing that's a topic for my advanced react course we also have indexed ojs which is the entry point for our application don't worry about the code here we're gonna write it from scratch in the next lecture similarly we have index the CSS you also have logo that SVG which is the logo of our application and finally register service worker that jas this is some code that is automatically generated by create react app and it may change or disappear in the future but at the time of recording this basically what this file does is it serves assets from a local cache in a production environment so for now we don't have to worry about this next I'm gonna show you how to write some react code from scratch all right now I want you to delete all the files inside of the source folder you're going to write everything from scratch so let's start by adding a new file here call it index the j/s here we need to import a couple of objects from react modules so if you're not familiar with es6 modules don't worry just code along with me we'll get to them in the next section so import react from react so this is the module and this is the object that we're importing from that module the other object we need to import is react dumb and we're going to import this from react - dumb now let's define an element so const element const is a new feature in modern JavaScript previously we used on Ivar but now we have const and let again in the next section i want to give you a quick overview of all these new features so let's define a constant element and set it to a JSX expression so h1 hello world and close h1 now as I told you before babel will compile this down to a call to react that create element and this is the reason why we have to import react on the top even though we're not going to directly use this object in our code but when our code is compiled because there is a reference to react that's why we have to import it on the top now let's log this element on the console so here is one thing you need to know about projects that are created we create react app whenever you save the changes this application is automatically restarted so you don't have to go back in the browser and refresh it this is what we call hot module reloading so save the changes now back in the browser you can see I didn't refresh the page and that black banner that we had on the top is now gone now open up the console you can do that using alt command an eye on Mac or alt control eye on Windows if short-cut doesn't work for you go to the view menu on the top developer and developer tools so here on the console tab you can see we have an object this is the output of a JSX expression this is a react element so you can see the type of this element the type property is set to h1 and we have a bunch of other properties here so earlier at the beginning of the course I talked about virtual Dom which is a lightweight in-memory representation of the UI it's not the real browser Dom it's the virtual DOM and this object you see here this react element is part of that virtual Dom so whenever the state of this object changes react will get a new react element then react will compare this element with the previous one it will figure out what is changed and then it will reach out to the real Dom and update it accordingly ok so here we have a JSX expression the result of that is a react element which is part of the virtual gun now we want to render this inside of the real gun and that's why we have to import react Dom on the top so here we call react Dom dot render as the first argument we pass the element we want to render so here's our element object as a second argument we need to specify where in the real dumb we want to render this so temporarily let's go back to the public folder here in index dot HTML earlier I talked about this div div with the ID root I told you that this is the container for our react application so back to index j s you need to use plain vanilla JavaScript to get a reference to that Dom element so we call document that get element by ID and here we pass the ID that is root so this react Dom will get a reference to this and render this react element inside of that element save the changes back in the browser you can see our hello world message let's right-click this and inspect it in chrome developer tools here you can see our div with the ID root and inside of this day we have our react element h1 with the tanks hello world this is a very simple application in a real world application instead of rendering a simple element in the Dom will render our app component this app component is the root component for our application it includes children like navigation bar sidebar profile and whatnot so we'll have a tree of components which will eventually produce a complex Markov hi guys thank you for watching my react tutorial over the next section we're going to explore react components in detail and in that section we're going to use some modern JavaScript features if you're not strong in JavaScript and find that section confusing I highly recommend you to watch my JavaScript tutorial for react developers you can find the link on the top right corner of the screen here also I wanted to let you know that this react tutorial is part of my complete 10 hour react course in that course we'll build and deploy a real video rental application with react from scratch so by the end of watching the course you'll be able to build react applications on your own and you will also receive a certificate of completion in case you're interested to enroll you can find a link in the video description below alright now let's continue to the next section [Music] all right we are ready to start learning react so over the next two sections we're going to build this application at the first glance you may think this is stupid but this is actually the pattern behind items in a shopping cart so imagine each row we have here represents a product here we have the quantity of that product and the shopping cart we also have buttons to change that quantity note that if the quantity reaches zero this decrement button becomes disabled also we're displaying the quantity in a yellow badge so you will learn how to render content dynamically how to apply CSS classes dynamically we also have this delete button for removing an item from this list we also have another button for resetting the quantity of all the items to zero and finally we have this badge on the navigation bar which is like e-commerce application so as you add items in the shopping cart it shows the total number of items in the shopping cart but in this application it behaves a little bit differently it only shows the number of counters with value greater than zero so currently we have three counters but only the first one its value is 1 and that's why we have one in the navigation bar if I increment the value of the second counter now we have two in the navigation bar so this simple application exhibits patterns that you see in a lot of real-world applications now let's get started you all right let's start by creating a new project so here in the terminal or command prompt let's run create react app and give our application a name counter - app okay beautiful our new project is ready so let's go to this folder counter app and start the application okay beautiful now here in vs code the first thing we need to do is install bootstrap in case you are not familiar with bootstrap it's basically a CSS library that gives our applications a modern look and feel now to install bootstrap we need to go back in terminal but if you look here in vs code we have this shortcut toggle terminal on Mac the shortcut is ctrl + backtick so let's open that up here so here we have an integrated terminal we can run NPM install bootstrap make sure to install the same version I'm gonna install in this video so version 4.1.1 okay beautiful now finally we need to import this in index j s so let's open up index j s here on top we need to add another import statement so import quotes here in the intellisense you can see bootstrap so let's go to this folder and then dist which is short for distributable then CSS and finally bootstrap dot CSS so this is how we import bootstrap CSS in our application save the changes back in the browser you can see the font is changed next we're going to create our first component alright now let's create our first component so here in the source folder let's add a new folder components by convention we put all our components here now in the components folder let's add a new file we call it counter the JSX note that here I'm using camel notation so the first letter of the first word should be lowercase and the first letter of every word after should be uppercase so if you wanted to call this file counter component you would name it like this counter component with a capital C okay also I highly encourage you to use the JSX extension instead of just j/s because with this you would get better code completion so here's our counter module in this module on the top we need to import react and the component class from the react module we can manually type it by hand or let me show you a shortcut to generate this line earlier at the beginning of the course I told you to install an extension called simple react snippet so here on the extensions tab under installed you can see of God simple react snippets this is a very powerful extension it has a lot of shortcuts to quickly generate code you can find all the shortcuts below in this video I'm gonna use a couple of these shortcuts one is IM RC for generating the import statement and the other is CC for generating a class component so I can counter that JSX type IM RC which is short for import react component and press tab done next type CC which is short for create class tap done now here we have multiple cursors so what we type is reflected in both places let's give this component a name so counter with a capital C now to stop Multi cursor editing press the escape button so we have counter class that extends the component class that we imported on the top from the react module this component class has a bunch of methods that we're going to inherit in this counter class okay now this code also generates the state property in this video we don't care about this we're going to look at that later in the section so delete it and modify the render method to return a simple h1 with the text hello world now to refresh your memory what we have here is a JSX expression it's not a string it's a JSX expression which eventually gets compiled to calls to react that create element that's why we have to import the react object on the top even though we're not going to directly use this in our code okay so let's delete this line so we have a simple component that when rendered returns an h1 element right now note that in this generated code we are defining the class here and then exporting it separately on line 9 this is different from what I showed you in the last section where I talked about modules there we define a class and exported it on the same line so here we can do something like this export default class counter and then we can delete what we have on line 9 but going forward I prefer to stick to the template that is generated by this extension so I don't have to modify it every time okay so let's revert this back we're done with this component now let's use it so save the changes we need to go to index J s so on the top we can type in dexter j s and if you're curious how i brought up this little panel you can find a shortcut here under the go menu so on Mac its command + P on Windows I'm not sure you need to find it yourself so let's go to index J s here we need to import our counter class so import counter from period slash components slash counter I note that because counter is a default export we don't need curly braces around it okay now finally on line nine where you're rendering a react component instead of the app component we're gonna render our counter component so you can see with this components we are extending the HTML vocabulary so wherever we have a counter element will get the output of the counter component which is determined by what is returned from the render method now back in the browser we can see our counter component rendered in the DOM properly alright now let's add a button here so right after h1 I'm going to add a button we set the innertext to increment now it can immediately see a compilation error here you have a red underline JSX expressions must have one parent element why is that well earlier I told you that these JSX expressions get compiled to a call to react but create element now the first argument to this method is the type of the element that we want to create in this case h1 but when we have two elements side by side Babel doesn't know how to compile this long expression into a call to react or create element what is the type of the react element that should be returned from the render method we can tell so one solution is to wrap this with a div so let's add a div here and close it at the end now when babel sees this it will compile this expression down to something like this so we'll have a react element with the type div and inside of that element we'll have two other elements an h1 and a button okay so delete now see what happens when I save the changes the prettier extension that I told you to install at the beginning of the course automatically reformatted this expression now it's more readable and it also put parentheses around that this is essential because of something that we call automatic semicolon insertion so in JavaScript if you have a return statement and nothing in front of it JavaScript will automatically put a semicolon here so if you add a div on the next line javascript is not gonna see that it thinks you have a return statement with nothing in front of it to solve this problem we should put a parenthesis right in front of the return keyword and then close it at the end of our JSX expression okay so delete now the thing is that whenever you're dealing with a long JSX expression as soon as you save the file this prettier extension would automatically put these parentheses for you so you don't have to do it manually all right save the changes now back in the browser here's our button let's inspect this so here we have this div with the ID root this is coming from our index dot HTML I showed you this at the beginning of the course so this is the div or the container for our react application inside of this div we have this other div which we added a minute ago to wrap our h1 and button elements okay now sometimes you don't want an extra div that is not doing anything here in that case you can use react dot fragment let me show you so back in the code we imported this react object on the top this react has a child called fragment so we can replace these two divs with react dot fragment now if you're curious how I edited both these instances at the same time this is called multi cursor editing so we can select a piece of code press command + D on mac or control-d on windows to find another occurrence of that selection now if you have more occurrences you keep pressing command + D or ctrl T now we have multiple cursors we can change all instances in one go so react fragment now save the changes back in the browser this time inside of our root div we only have the h1 and the button they are not contained by another div alright now let's take this to the next level instead of hard-coding is hello world here I want to display a value dynamically so here in the counter class we need to add a property call it state and set it to an object state is a special property in react component and basically it's an object that includes any data that this component needs so in this case let's add a property in this object call it count and set it to zero now here we could have a complex object for example we could have an address that could have a street property like this so basically this state object includes any data that this component needs in this example all we need is a count property so let's simplify this now I'm gonna replace h1 with a span so I've selected h1 and I'm pressing command + D now we have multiple cursors let's change both instances to span done now let's remove hello world here we want to render something dynamically to do that we add curly braces and in between these curly braces we can add any valid JavaScript expressions so if you want to render the value of the count property here we would write code like this this to reference the current object dot state dot count now save the changes you can see the result here so this is our count if I change this to 1 save the changes now we see one here beautiful now as I told you in between these curly braces we can write any valid JavaScript expressions an expression is something that produces a value for example we can write something like 2 plus to save the changes we get 4 here or we can call a function that returns a value for example let's add a method in this class call it format count in this method you want to check the value of the count property if it's zero we want to return zero as a string otherwise you want to return the value of the count property itself so we can do something like this return this that state that count if it equals zero we're gonna return the labeled zero otherwise this that state dot count now before looking at the result I want to quickly improve this code look we have this repetition of this that state the count whenever you have code like this that's a perfect opportunity to use object destructuring that you learned about in the last section so we can do structure this object and pick the count property like this Const we add curly braces count we set it to this that state so we're picking the count property of this object and storing it in a separate constant called count now I'm gonna select this expression press command + D so both these expressions are selected now let's change both of them to count that is better save the changes and finally back here let's call this that format count now save the changes so currently our count is 1 that's why we see one here let's change this to 0 save the changes we get the labels 0 now to take this to the next level we can also return a JSX expression here because as we told you before JSX expressions get compiled to react elements so here instead of returning a plain text we can return h1 with 0 as the inner text so save the changes now we have an h1 here so this is what I want you to understand JSX expressions are just like normal JavaScript objects you can return them from a function you can pass them to a function you can also use them as the knew of a constant or variable so here I can define a constant and set it with JSX expression that's perfectly fine so now let's simplify this code we don't need this anymore and here on line 19 I just want to return 0 as a plain text next we're gonna look at setting attributes in this lecture you're gonna learn how to set attributes on these elements for example let's add an image here we want to set the source attribute if you have couch here whatever we type in between the code is rendered as plain static text in this demo you want to set the value of the source attribute dynamically so let's add a property in this state object call it image URL and set it to something like this HTTP pick some photos / 200 this will generate a random 200 by 200 pixel image now back to our image element let's replace the quote with braces and the last lecture you learned that we can use this braces to render values dynamically so here we want to render this dot state dot image URL save the changes this is what we get beautiful now back to our code so setting attribute is pretty straightforward but let's look at setting the class and style attributes because they are a little bit different so I'm gonna delete this image element as well as the image URL let's say we want to apply a class to this span element the name of the attribute is not class its class name because as I told you before these JSX expressions get compiled to react elements which are essentially plain JavaScript objects we cannot use a class property on an object because that's a reserved keyword in JavaScript so the name of the attribute in JSX is class name here I'm gonna use a couple of bootstrap classes one is badge and the other is badge - primary save the changes this is what we get a blue badge now this badge this span is pretty close to this button we can add a bit of margin to let the UI breathe back in the code the name of the class is M - - so of margin to save the changes now you can see there's a bit of space in between the span and the button that looks better now similarly let's apply a class to this button so back in the code here's our button class name we set this - BTN be TN - secondary add BTN - SM which is short for small now if these classes are unfamiliar to you you need to look at bootstrap documentation that's an entirely different topic we cannot talk about it in my react course so save the changes and now our button looks different that's much better now finally let's look at applying styles so for the most part it's best to use classes this is for performance and maintainability but there are times that you may want to break the rules if you know what you're doing and you may want to apply your style to a specific element now in JSX we have this style attribute that we need to set to a plain JavaScript object so first we need to add curly braces here now in between these curly braces we need to pass a plain JavaScript object here's one way to do this we can define a property called it styles set it to an object the properties of this object are CSS properties in camelcase notation for example font weight so the first letter of the first word is lowercase but the first letter of every word after is uppercase now we can set this to a numerical value like 10 and react will automatically convert this to something like this so it will append pixels to yet actually this should be font size not font weight so font size 10 pixels or just a numerical 10 and we can also set font weight to bold now we can pass this object here so this not styles save the changes now you can see our text is a little bit smaller and bold to demonstrate that this is actually working let me change this to let's say 50 save the changes and now we have a big badge here so this is one way to apply styles we define a property here and then reference it in our JSX expression but maybe you want to apply us to a couple of different elements so you don't want to define multiple properties in this class if that's the case you can use inline stats so here in between this curly braces we can just pass an object and set the properties on that object so let's say font size 30 now we don't need this Styles property anymore let's save the changes with this syntax we'll get double curly braces now back in the browser you can see our badge its font size is now 30 in this section we're only gonna use the classes so I'm gonna delete the style attribute done next we're going to look at rendering classes dynamically our badge is currently blue but let's change this application such that if the value of the count property is zero we want to render this as yellow to indicate some kind of warning otherwise we want to render it as blue so back in the code let me use the badge primary class here we get a blue badge if we use badge warning we'll get a yellow badge so in this lecture we want to render in one of these classes dynamically depending on the value of the count property and this is a pattern that you see a lot in real-world applications so here's one way to do this we can define a constant here call it classes set it to a string in this string we're going to include all the classes that we're going to pass here so we start with the primary classes that we want to have in all cases that is badge and m2 so badge and m2 now depending on the value of the count property you want to add badge warning or batch primary to this string so classes plus equal now note that we're modifying this so we cannot use a constant that's when we use the let keyword so if this that state that count equals zero we're gonna append badge - warning otherwise we're gonna append badge - primary now we could make this a little bit cleaner so we don't want to repeat badge - in a couple of places we can add that here badge - and here on line 10 simply append warning or primary and finally replace these hard-coded classes with what we have in this variable so save the changes initially our count is zero that's why we have a yellow badge but if we go back here and change the value of count to 1 save the changes now we get a blue batch awesome but we're not done yet look at our render method these two first lines are purely about determining the class for this label there are polluting a render method it would be nicer if we encapsulated these two lines in a separate method so the details of calculation of the classes is not causing this method to get bloated so let's extract these two lines in a separate method now let me show you a quick tip I'm gonna select these two lines right click look at this refactor menu note the shortcut on Mac is ctrl shift + R so I'm gonna use this shortcut and this brings up the refactoring menu so here we have a refactoring command called extract - method in class so let's go ahead with that now you can see vs code automatically extracted these two lines into a separate method now we need to give this method a name let's call that get bad classes always use descriptive names that determine the intention of your code this makes it easier for other developers to read and understand your code okay so here's our new method now we can simplify this code we don't need this separate variable here we can call this method directly right here so this that get badge classes and then we delete this variable now we can see our render method is cleaner it's not bloated but various responsibilities save the changes to make sure everything is working our badge is blue beautiful finally let's change this to zero save the changes and now it's yellow perfect next we're gonna look at rendering lists in this lecture you're going to learn how to render a list of items so let's imagine we want to render a list of tags here we start by adding a new property to our state object tags we set it to an array of three strings tag one tag two and tag three now here in a render method we want to render these tags using ul and Li elements now if you've worked with angular you have seen the ng four directive we use that to implement a loop in our templates but in react in JSX expressions we don't have the concept of loops because JSX is really not a templating engine it's just a simple syntax that will eventually get compiled to react elements so how can we render a bunch of list items here well in the last section I talked about the map method of a race we can use the map method to map each element in this array into a react element and with this we can render a list of items let me show you so here you want to render something dynamically so we start with curly braces next we get this that state but tags this is an array so here we have a map method now as the argument we need to pass an arrow function tag goes to now we get each tag and map it to a list item as simple as that so basically what we're doing is we're getting a string and mapping it with j6 expression which gets compiled to a react element which is essentially a plain JavaScript object so even though the syntax here looks a little bit funny what we're doing is taking a string and mapping it to a plain JavaScript object right now here in this JSX expression you want to render the tag dynamically so once again we add curly braces and render the tag as simple as that so this is how we render a list of items in react let's save the changes back in the browser so here are our tags beautiful however if you look at the browser console you should see this error each child in an array or iterator should have a unique key the reason react is yelling at us here is because it needs to uniquely identify each item in this list because if the state of this react element and the virtual Dom changes react needs to quickly figure out what element is changed and where in the Dom it should make changes to keep the Dom in sync with the virtual Dom so back in the code whenever you are using the map method to render a list of items here for each item you need to set the key attribute so key we set this to a dynamic value here each tag is a string and that string is unique so we can use the same value for the key attribute now in a real application your tags might be objects so they could have an ID property then you would use that here now just note that this key should only be unique in this list that it's the list of tags it doesn't have to be unique in the entire application or on the entire page you could have multiple lists and each item in a given list should have a key that is unique only in that list ok now save the changes back in the browser you can see the warning is gone in this lecture you're going to learn about conditional rendering now to help us focus only on a single thing I'm gonna temporarily clean up this code so in the render method we don't need the span and the button let's delete those also we don't need these two helper methods in the class either so let's focus on something really simple so we have an array of items and be rendering that in a list here's a new requirement if this array has at least one element we want to render that array in a list otherwise we want to display a message like there are no tags how can we implement this well once again in JSX unlike angular we don't have if and else because JSX is not a templating engine so to render elements conditionally we need to go back to our plain old JavaScript here's one way to implement this scenario we can add a separate helper method like render tags in this method we can have our if and else statements so if this that state the tags that length equals 0 we got a return some text like there are no tags and of course instead of returning just plain text here we could return maybe a paragraph we're returning a JSX expression which is a react element so there are no tags or if you don't want to display anything is simply return no ok so this is the case for an empty array otherwise we would have rendered the array using ul and Li elements so I'm gonna cut this code from here and simply return it in our method finally in our render method we add curly braces and call this the render tags so depending on our state this method will return either a paragraph or an unordered list with a bunch of list items pretty straightforward right save the changes back in the browser currently we have three tags so we see them here now back in the code if I empty this array and save the changes we get this message there are no tags there is also another technique for conditionally rendering content let me show you so back in the code here in a render method just before rendering the tags let's imagine you want to render a separate message based on a given condition so we have only a single if statement without an else part okay so we can add our curly braces here right the condition let's say this that state the tags that length equals zero if that's the case we want to render an additional message we add our logical and operator here and then whatever we want to render we add that here let's say please create a new tag save the changes back in the browser so here is our message please create a new tag this is rendered only if our array is empty now let's investigate how this expression works under the hood so here we're applying the logical and operator between two values the first value is the result of this expression which is a boolean it's either true or false and the second value is a string in JavaScript unlike other programming languages you can apply the logical and between non boolean values so let's go back to the browser and open up the console here the console I'm gonna write plain JavaScript code if you type true and false we get false what if you type true and a string like hi what do you think we're gonna get we get hi here is the reason when javascript engine tries to evaluate this expression it looks at the first operand in this case the first operand is true so it will look at the second operand the second operand is not a boolean true or false so the JavaScript engine tries to convert this into what we call true C or false see an empty string is considered false see a string that has at least one character is true C so in this case hi is considered true C so essentially we have two operas that are both true C in that case our JavaScript engine will return the second operand let's take a look at another example so true and high and a number once again the first operand is true C so the evaluation of this expression will continue the second operand is also true C so the evaluation continues now we get to the third operand in JavaScript number zero is considered false see any numbers but zero is considered true C so once again here we have three true C operands and the result of this expression will be the last operand so we get one so back to a render method to conditionally render content we can use the logical and operator first we have our condition then and and then whatever we want to render after comes here it can be plain text or another JSX expression now let's see how you can handle events so all these react elements have properties that are based on standard Dom events for example here in our button we have a property on click you also have on double-click if you're working with input fields you have on key down on key press on key up all those standard Dom events that you are familiar with so here let's handle the on click event we set this to curly braces because we need to pass an expression now the way we do this is by defining a method here and the naming convention we use for that is handle what are we handling here increment so handle increment let's do a console that log increment clicked and then finally we need to pass a reference to this method here in between curly braces so this dot handle increment note that we are not calling this method you're simply passing a reference to it this is different from handling events in vanilla JavaScript in vanilla JavaScript we call the target function when setting the unclick attribute also note that the name of the event here is case-sensitive so if we use a lowercase C here we're gonna get an error because react elements don't have a property called on click with this naming convention okay so let's revert this back save the changes as you can see the prettier plug-in automatically reformatted this code so now each attribute or property is on a separate line now back in the browser let's click this button there you go we get these messages here beautiful now here in this method we need to increment the value of the count property but currently there is a problem with our implementation so if we log this that state that count we're gonna get an error let me show you so here let's lock this that state that count save the changes back in the browser click there you go cannot read properties state of undefined so back in the code this is undefined in this method let's verify that so let's just log this on the console one more time let's click this you can see this is undefined so currently we don't have access to the state property why that's the topic for the next lecture so in the last lecture you learned that in this event handler we don't have access to this why is that well earlier in the last section you learned that this in JavaScript behaves differently from other languages so depending on how a function is called this can reference different objects if a function is called as part of a method in an object this in that function will always return a reference to that object however if that function is called as a stand-alone function without an object reference this by default returns a reference to the window object but if the strict mode is enabled this will return undefined and that's the reason in this event handler we don't have access to this so what is the solution again in the last section I talked about the bind method we use that method to solve this problem let me show you so here in this class we're gonna add a constructor this is a method that is called when an object of this type is created so in the constructor at this point we do have access to this so let me show you here I'm going to do a console dot log saying here we are in the constructor let's see what is the value of this save the changes back in the browser we get this error that you have seen before this is not allowed before super so because we added a constructor in this child class first we have to call the constructor of the parent class using the super keyword so recall super save the changes back in the console now we can see in the constructor we do have access to our counter object so this is not undefined at this point so this is a perfect opportunity to use the bind method so let's remove this line and type this then handle increment so earlier you learned that functions in JavaScript are objects so they have properties and methods one of them is the bind method and with this method we can set the value of this so I'm going to use this here and this point method will return a new instance of the handle increment function and in that function this is always referencing the current object so no matter how that function is called this is not gonna change it's always referencing the current counter object so this method returns a new function we can get that function and reset handle increment like this so this that handle increment we set that to the function that is returned from the bind method okay so save the changes now back in the console when we click the increment button we no longer see undefined here so we have access to the current counter object and with this we'll be able to update the state property so here's one solution to bind event handlers to this but you might find this a little bit noisy because in every component you have to add a constructor you have to call the base constructor and for every event handler you have to write code like this there is another way to solve this problem this is currently experimental and it may break in the future so let's see how that works instead of adding this constructor we can convert this function into an error function once again in the last section I told you that arrow functions don't remind that this keyword they inherited so we can set this to an error function and this will solve our problem save the changes back to the browser let's call this button we get our counter object perfect so you can see using an arrow function is cleaner and simpler than adding a custom constructor and rebinding every event handler manually so going forward I'm gonna use this syntax but if this feature is not available at the time of you watching this video use the former approach to bind event handlers now that we have access to the current object in our event handler it's time to update the value of the count property so in react we do not modify the state directly in other words we don't write code like this this that state that count plus plus plus it's not gonna work let me show you save the changes back in the browser click this button see nothing is happening well technically the value of the count property is being incremented but react is not aware of that that's why it's not updating the view to solve this problem we need to use one of the methods that we inherit from the base component in react so we call this dot set state this method tells react that we're updating the state then it will figure out what part of the state is changed and based on that it will bring the Dom in sync with the virtual Dom this is different from frameworks like angular in angular we don't have to do this angular automatically detects the changes because in angular all browser events are monkey patched so whenever you click a button or type something in an input field angular is notified it runs its change detection algorithm it figures out what is changed and it will update the view react doesn't work that way we have to explicitly tell react what is changed so here has the argument to set state method we pass an object and the properties of this object will be merged with what we have in the state object or it will override those properties if they already exist so here I'm gonna pass the count property and I want to set its value to this that state that count plus 1 so we get the current count increment it and then set it now let's delete what we have on line 9 save the changes back in the browser let's click this button you can see our count is incremented because react is aware of the state changes now that you have seen a complete example of a component let's see what exactly happens under the hood when we click the increment button at this point we're calling this that set state this method is telling react that the state of this component is going to change react will then schedule a call to the render method so sometime in the future this method is going to be called we don't know when this is an asynchronous call which means it's going to happen in the future it may happen 5 milliseconds later or 10 milliseconds later we don't know so at some point in the future the render method is going to be called this method as you can see will return a new react element that element is this div that we have on the top this react element has two children a span and a button so our virtual Dom is a tree of three elements a react element on the top and is our div with two children okay so here's the new virtual Dom we also have the old virtual Dom react will put this side-by-side and compare them to figure out what elements and the virtual Dom are modified in this case it realizes that our span is modified because that's where we have used the count property so it will reach out to a real browser Dom and update the corresponding span so it matches the one we have in the virtual Dom so nowhere else in the Dom is updated only that span element let me show you so here I'm gonna right click on our badge inspect it is what we have in the dawn now every time I click the increment button you will see that only the span element is updated so click see you can see only the span element is highlighted and nothing else in the Dom is affected currently our handle increment method does not take any parameters but sometimes in real-world applications we need to pass arguments with our events for example let's imagine here we're dealing with a list of products in a shopping cart when we click the handle increment button we want to pass the idea of a product how can we do this well earlier you learned that in unclick we need to pass a function reference so here we cannot call handle increment and pass an argument like 1 we need to pass a function reference so here's one solution we can temporarily define another method here let's just call it do handle increment for argument's sake that's similar to handle increment we're going to use the error function syntax so we have a function with no parameters in this function we can call this that handle increment with an argument let's say that argument is a product object with the ID 1 now we can modify handle increment and add a parameter call it e as in short for event or product whatever that parameter is representing now we can lock this on the console ok and finally in our render method instead of referencing this that handle increment we can reference this the do handle increment right back in the browser when I click the increment button you can see our product object which is the argument to the handle increment method so this was one simple solution but writing code like this is messy we don't want to redefine another similar method as a wrapper just to pass an argument to the actual event handler a better solution is to use an inline function here so in unclick instead of referencing this the do handle increment we can simply pass this arrow function in between curly braces so we write code like this no parameters goes to this that handle increment and then we pass an argument now when rendering a list of products in a shopping cart in our map method we have access to a product object so instead of hard-coding this object here it will pass a reference to the product that we're currently rendering okay with this we no longer need this helper method so to recap whenever you need to pass an argument your event handlers simply pass an error function here in the body of that function called the event handler and pass an argument in this section you learned the essence of react components more specifically you learn about JSX or JavaScript XML syntax for describing the UI you learned about rendering lists conditional rendering as well as handling events and updating the state of components in the next section we're going to look at composing components to build complex user interfaces so I'll see you in the next section [Music] in the last section we worked with single components when a real-world application consists of a tree of components so in this section we're going to look at composing components in react more specifically you're going to learn how to pass data between your components you're going to learn how to raise and handle events how to have multiple components that are in sync as well as functional components and lifecycle hooks these are all very important topics that you'll use quite a lot in real-world applications by the end of this section you will have a very deep understanding of react components are you ready now let's get started [Music] you [Music] so far in this application we have worked with a single component so if you look at index that j/s you can see we're rendering a single counter component in the Dom but as I told you before every active application is essentially a tree of components so we can compose components together to build complex user interfaces and that's what we're going to do in this lecture so I'm gonna add a new component to our application here in the components folder let's add a new file counters the JSX in this component I'm gonna render a list of counters and then in index at j/s instead of rendering a counter component I want to render a counters component with this change our component tree will look like this ok so back in index to j/s instead of importing the counter component let's import counters from the counters module and render that here now back to our new component on the top I MRC tab CC tab let's call these counters ok now in the render method let's add a div this is going to be the wrapper or the container for all our counters because we want to return a single element from the render method right so here you want to add multiple counter components first on the top we need to import the counter component from the current folder counter module now here let's render if you counter components save the changes back in the browser you can see we have multiple counter components each component has its own state that is completely isolated from the other components beautiful now let's take this to the next level instead of hard-coding this counter components here let's add an array of counter objects to our state property and using the map method so here let's add and your property counters we set it to an array in this array we're going to have counter objects like this each object should have an ID property and we're going to use this to uniquely identify each counter we should also have a value property and will later use this to set the initial value for each counter for now I'm going to set this to zero now let's duplicate this multiple times and change the IDS okay beautiful finally let's get rid of these counters instead you want to render an expression here this that state that counters the map we get each counter and map it to a counter component also we should set the key property to counter dot ID save the changes we still get the same output and each counter has its own state beautiful however all our counters are initialized to zero and the value that we set here is not applied to this counter components so if I change the value of the first counter to 4 we still get a counter initialized to 0 we'll fix that in the next lecture in the last lecture we set the key attribute to counter that ID using the same syntax we can set additional attributes here and with this we can initialize our counter components so I'm gonna put this on a new line so you can see clearly now let's add a couple more attributes here so I'm gonna set value to counter that value and also select it I'm gonna set this to true for now I have hard-coded this value potentially in the future this can be set to a property in our counter objects now back in our counter component here the render method I'm gonna temporarily add a consult log and show you this got props so every react component has a property called props and this is basically a plain JavaScript object that includes all the attributes that we set encounters component so these two attributes value and selected will be the properties of that props object key will not be part of that because this is a special attribute for uniquely identifying elements so now the changes and go back to Chrome you can see we have four messages on the console because we have four counter components look at the first message our props is an object with two properties value which was set to four and selected which was set to true so now we can read this value and use that to initialize each counter component so back in our counter component instead of initializing the count property to zero I'm gonna set it to this the props dot value save the changes back in chrome you can see our first counter is initialized to four beautiful so here in the render method we no longer need this line let's delete that also I would like to rename this count property to value to be consistent with the property that we are setting from the outside this makes our code cleaner and more maintainable we don't have to do all the guesswork to remember what name we used where so put the cursor here press f2 and rename this to value we should also rename this count property to value so it's more meaningful to say a counter has a value as opposed to a counter has a count now one more thing before we finish this lecture back in our counters component here I've set select that to true if I exclude the value by default it will be set to true now going forward we don't need this attribute so I'm going to delete it you in the last lecture you learned that the attributes that we said here are passed to our component using a single JavaScript object called props now we have a special prop called children and we use that when we want to pass something between the opening and closing tag of an element so here counter is self closed but sometimes we want to pass content in between the opening and closing tags maybe we want to pass an h4 here with some kind of title like this a real world example of this is when using dialog boxes imagine instead of the counter component you have a dialog box component and you want to allow the consumer of that component to pass content to be rendered on the dialog box so let me show you how to do this save the changes now back in our counter component one more time in the render method I'm gonna show you the props property so console that log of this props now back in the browser so here's our props object you can see we have the value property just like before but we have a new property called children let's take a closer look so children is essentially a react element as we can see here the type of this react element is h4 so back in our counter component here in the render method we can simply render the children prop so here inside this div right before our span I'm gonna render this props the children as simple as that save the changes now you can see each counter has a title we can also make this dynamic so here in counters component instead of hard-coding this title we can do something like this counter number and then render counter that ID dynamically and here's the result now in this particular example we didn't really have to use the children we could simply pass the ID as another attribute you can set that here counter that ID and in our counter component because simply render an h4 that includes this but props then ID will get the same result but as I told you earlier there are times that you want to pass complex elements to a child component such as a dialog box in those cases you use the children prop now going forward we're not going to use that children props so I'm gonna delete the code that I wrote in this lecture so back in our counters component let's delete the children done you in this lecture I'm going to introduce you to a very useful tool for debugging react applications this tool is currently available as an extension for Chrome and Firefox and as a standalone app for Safari and Internet Explorer so if you're using Chrome or Firefox simply search for react developer tools when you install this you will see a new tab in chrome developer tools so here in our react application let's open up chrome developer tools here you can see we have a new tab react on this panel you can see the tree of our components so on the top we have the counters component when you expand that you see a div and below that you will see all our counter components similarly you can expand each counter component to see its content so here we have a div with a span and a button now why is this useful well let's go on the top and select the counters component on the right side you can see the props and stayed for this component so in this component we don't have any props so our props is an empty object but our state has a counters property which is an array of four objects let's take a look at the first counter you can see the key is set to one our props object has two properties ID and value and our state object has a value property which is initialized based on props that value so this panel makes it really easy to visualize what's going on on the page what are various components what is the state of each component and so on you also have this search bar here so if you're working on a complex page with several components you don't have to expand them all here you can simply search for that component in the search bar another useful feature here is this dollar R so note that as I select each component here we get this equal equal dollar R what is this well I'm going to select the first one you know that in the first component R value prop is for now if we go to the console tab and type dollar R look we get the instance of our first counter component so let's expand this look at the props here we have an object with two properties value which is for an ID which is one so with this daughter R we can work with the instance of any components on our page let's look at another example here I'm gonna type dollar r dot render I'm gonna call the render method you can see we get every act element which is a plain JavaScript object the type of this element is div because here the render method you're wrapping the content of our counter with a div so that's why the type of the react element that is returned from this method is div now this dollar our feature is not limited to react we have something similar in the elements tab but a lot of people are not aware of that so here in our elements panel let's scroll down expand our route div expand this again here's our first counter find the button select that you can see we've got equal equal dollar zero similarly we can go to the console tab type dollar zero and this returns that button element and the Dom we can do something like this dollar zero dot click we can click the button and now we can see the count is five let's execute this one more time now the count is six so have react dev tools in your toolbox it makes it really easy to build and debug react applications so here in the counter component we're using props to initialize the state one of the things that confuses beginners to react is what is the difference between props and state so in this lecture I'm going to clarify this props includes data that we give to a component whereas state includes data that is local or private to that component so other components cannot access that state it's completely internal to that component in other words if we go to our counters component this is where we're using the counter component all the attributes that we're setting here these attributes are part of the props the input to the component we cannot access the state of this component the state is local and internal to that component similarly this counters component has its own local state which is completely invisible to other components now sometimes a component may not have a state it may get all the data that it needs via props and you're going to see that later in this section one more thing you need to know about props versus state is that props is read-only in other words we cannot change the input to this component inside of this component let me show you so if we go back to our counter component here in handle increment I'm gonna change one of the properties of the props object so this the props that value I'm gonna set that to zero let's see what happens when we click the increment button so here I'm gonna click this button we get this error cannot assign to read-only property value of object so react does not allow you to change any properties of the props object it's purely input to a component and we should not modify the input if we need to modify that input during the lifecycle of a component then we need to get that input and put it in this state in this case our counter component has its own local state so we can modify this value in or handle increment button as we have done here so let's delete this line next we're going to talk about raising and handling events now let's take this application to the next level I want to add a delete button next to each counter so here in our counter component in the render method right after our increment button I want to add a new button so a button with a few classes BTN BTN - danger to make it red BTN - SM to make it small and M - - to add a bit of margin around this button and the increment button now let's type the label delete save the changes back in the browser here's our delete button beautiful now let's handle the click event so here we want to add on click and set it to a method in this class like this that handle delete however if you look at the state of this component you can see in this state object we only have the value property but in order to delete a counter we need to delete it from this array of counters that we have in the counters component and this brings us to a very important rule of thumb in react applications the component that owns a piece of this state should be the one modifying it in this particular example this piece of this date that is the list of counters is part of the counters component so modifying the state should be done by this component itself adding a new counter to this array or removing an existing one should be done inside of this component now in the last lecture you learned that the state is something private and internal to a component it's not visible to the outside so you might be wondering how can we modify this State from the counter component because this is where we have placed our delete button to solve this problem we should modify our counter component to raise an event we're gonna call that event on delete so our components can raise events and this is the naming convention we use to name those events so the counter component will raise this event and our counters component will handle this event in other words we should implement the handle delete method in the counters component not the counter component this concept of raising and handling events is something that you see in a lot of libraries for building user interfaces it's not specific to react now let me show you how to implement this concept in react basically we need to add a new method to our counters component and pass a reference to that method via props to the counter component so here in the counters component let's add a new method handle delete this is our event handler here let's do a simple consult blog event handler called now we want to pass a reference to this function using props to our child component that is our counter component so earlier we passed a couple of props here value and ID now we can pass another prop we're gonna call that prop based on the name of our event so the name of our event is on delete you're gonna set this to this that handle delete so now that we're passing a reference to this function to our child component let's go for a child component and modify this unclick expression so instead of referencing this that handled delete which does not exist in this component we want to reference this the props that on delete because that's the name of our prop right save the changes back in the browser here with the react tab open let's look at one of our counters look at the props now we have a new prop on delete which is a function so let's go to the console tab click this button we get the message event handler clicked so in this implementation our counter component is raising an event and is parent that is counters component is handling that event this is a very common pattern that you see in a lot of real world applications and you're going to see several more examples of this throughout the course but we are not done yet because in our handle delete method you're simply cancelled lock here we need to update the state and that's what we're going to do next to update the state we need to add a counter ID parameter here so we know which counter we need to remove from this list now to make sure that all the plumbing is gonna work before updating the state first let's just display counter ID on the console now we need to go back to our counter component here's our delete button we need to change this expression and pass the idea of this counter so as you have learned before we pass an error function and here we call on delete with this that props that ID now let's test this so back in the browser I'm gonna delete the first counter you can see the idea of that counter is one beautiful let's try another one that is counter with ID too perfect so now let's go ahead and update this date here in the counters component as I told you before in react we do not update the state directly in other words we are not going to remove a counter from this array instead we're going to create a new array without a given counter and then call the set State method of our component and let react update the state so here I'm going to define a new constant call it counters we're gonna set this to this that state that counters use the filter method to get all the counters except the one with the given ID so C goes to C that ID does not equal counter ID we have a new array so let's call this that set state has an object we want to overwrite the counters property with this counters constant also as I told you before here because the key and value are the same we can simplify this code like this now let's test this so back in the browser I'm gonna delete the first counter gun another one beautiful so our implementation is working but there is a tiny issue here that I would like to improve if you look at the render method of this component here we're passing three props to our child component on delete which is a function as well as value and ID now one question you might have is why do we have to pass ID and key while their values are exactly the same this looks like unnecessary repetition the reason for this is because this key attribute is used internally by react so we won't be able to access it in our counter component that's why we have to pass ID as a prop and then read it via this but props that ID now the tiny issue we have here is that we have passed value and ID as separate props both these are properties of the counter object if in the future we add a new property to our counter object we'll have to come back here and set a new prop like selected we set it to counter that selector and over time this is going to get messy and ugly the whole point of using objects is to encapsulate related values so instead of these three properties we could simply pass the counter object itself this object includes everything we need to know about a counter and also if in the future we had a new property to this counter object we don't have to come back here and modify this code our counter object is carrying all the data about a counter so with this change now we need to go back to our counter component and make a couple more changes here on line 23 this is where we have our delete button we need to change this expression we no longer have the ID property in our props object so we need to prefix this with counter similarly on the top where we initialize our state again we don't have the value property we need to prefix it with counter save the changes let's test the application so we can increment each counter beautiful and delete them perfect you we have an issue in our current team and that is that we don't have a single source of truth let me show you this using an example so here on the top I want to add a button for resetting all the counters so let's go back to our counters component here in the render method on top of all these counters let's add a button with a few classes BTN BTN - primary BTN - small and margin - are we gonna call this reset now let's handle the click event we're gonna set this to this that handle reset just like before nothing new so far and here I'm gonna implement handle reset we set it to an error function and in this method just like our handle delete method you want to create a new area of counters and call this that set State so we get the existing counters this that state that counters we use the map method to get each counter and reset its value to zero and then return it so with this we'll get a new array of counters let's store them here and then call this that set state with this new array so save the changes back in the browser let's click the reset button look nothing is happening here why is that the reason is because we don't have a single source of truth I'll show you what I mean so I'm gonna open up the chrome developer tools let's go to the react tab so here's our counters component look at the state for this component we have an array of for counter object if you look at one of these counters you can see it's value is 0 so we successfully updated the state but we are not seeing the changes in the Dom let's take a look at one of our counters so expand this here's our first counter look at its props we have this counter object that we passed from its parent look the value is zero but we don't see that on the view instead we see four so the issue we are facing here is that we don't have a single source of truth each of our components have their own local state our counters component has an array of counters and each counter component has a value this value is currently disconnected from the value property of each counter object that we have in this array here is the implementation of our counter component as you can see here we are initializing the value property of our state object based on what we get from our props this piece of code is executed only once when an instance of a counter component is created so that's why when the page loads we get the initial value here and we can increment it because this is a local state in our counter component but when we click the reset button the local state of this counter component is not updated so how can we fix this problem we need to remove the local state in our counter component and have a single source of truth and that's the topic for the next lecture so here in the counter component we want to remove the local state and only rely under props to receive the data that this component needs we refer to this kind of component as a controlled component a control component doesn't have its own local state it receives all the data via props and raises events whenever data needs to be changed so this component is entirely controlled by its parent so let's go ahead and do this refactoring first we're going to delete the state property next we need to find any references to this that state and update them accordingly the first reference is in our handle increment method so since we no longer have the local state it doesn't make sense to have this method here because this counter component is going to be a controlled component so whenever the data needs to be modified this component needs to raise an event and have its parent take care of modifying the data so delete here's our increment button instead of referencing the handle increment method which no longer exists by calling a method in the props object just like how we raised the undelete event here so let's get rid of this expression we're gonna pass an error function and in the body of this function we're gonna call this that props that on increment so that's the name of our event now as an argument we need to pass either the counter ID or a reference to this counter object I'm gonna pass a reference to the counter object because this will make the implementation of our event handler simpler as you will see in a few seconds so this got props dot counter it passed the inter counter object and let the event handler take care of incrementing the value of this counter now let's find any more references to this that state so we have two more references here that need to be modified one isn't get batch classes so here we need the value of the counter we can read that from this that props that counter here is the last reference so here we're using object destructuring to read the value property of the state since the state property is gone we're gonna read the value from this the props got counter so we're done with the removing of the local state of the counter component here we no longer have a state property and we're relying entirely on the props object to display data and notify changes now let's go back to our counters component we need to add a new event handler handle increment we set this to a function that takes a counter parameter for now let's just do a console that log of counter to make sure all the plumbing is working before we move on to update the state next we need to go to our render method so earlier we handled the on delete event now we handle on increment and we set this to this dot handle increment let's test the application up to this point so save and back in the browser I'm gonna increment our first counter so we get that counter object here with the value of four beautiful now we need to update the state just like before we are not going to update this state directly instead we should create a new counters array and give it to the set state method and have react update the state so let's create a new constant call it counters we set it to a new array and here I'm gonna use this spread operator to clone this that state the counters so we're cloning this array with this we'll get a new array of counters however the objects in this new array are exactly the same objects that we have in the counters array that we have in the state object let me show you so if we go to our new counters array get the first counter and increment its value this is going to directly modify the value property of this counter object that we have in the state so let's do a console that log of this that state the counters of zero save the changes back in the browser I'm gonna increment our first counter now you can see it's value is 5 so we have modified the state directly and this is a no-no in react to solve this problem we need to clone the counter at the given location so we'll have a different object than the one in the state we don't have to clone the other counter objects here because we're not going to modify them so we set counters of zero to a new object and once again we use the spread operator to clone this counter object that we receive as an argument here let's test the application one more time back in the browser now if I increment the first counter you can see the value is not updated so the counter object that we have in the state remains unchanged now here we are working with the first counter in this array instead we need to find the index of the counter that we receive as a parameter so let's define a new constant index and we set it to counters dot index off we pass our counter object and finally we replace all these zeros with index and the last piece is to update the state so we call this that set state and give it this new counters array let's test the application back in the browser I'm gonna increment the first counter beautiful let's delete some of these and click the reset perfect now let's take this application to the next level I want to add a navigation bar here on the top and then I want to display the total number of counters on this page you have seen this pattern before it's similar to displaying the total number of products in a shopping cart so as we add products to our shopping cart we can see the total number gets updated on the navigation bar so let's go ahead and implement this pattern back in vs code let's go to index j as you can see our route component is the counters component so here's a visualization of our component tree we have the counters component on the top and below that we have the counter component now we need to change this structure to something like this so we want to have the app component on the top below that we want to have a navigation bar and our counters component so back in index that J S on the top I'm going to bring back the app component and replace this counters component with app component now let's go to app component so app not Jas what we have here in the render method is the default black banner that comes with react project we want to replace this with a basic bootstrap template I showed you how to do this in the last section when we set up the wiggly project but let me quickly refresh your memory so we go to get bootstrap calm under examples if you scroll down you can see various templates I'm gonna pick a very simple starter template so we want to have a page like this now right click here go to view page source under body you can see we have a navigation bar and next to the navigation bar we have this main element with the class container this is the container for the content area of our application now we don't want a complex navigation bar like this so let's go back here go to documentation and search for nav bar on this page if you scroll down you can see a very simple navigation bar under brand so this is the layout that I'm looking for I don't want any links or drop down lists here just a simple navigation bar so here's the mark-up I'm gonna copy this now back in vs code we should create a new component for our navigation bar so a new file let's save this on there the components folder and call it nav bar the JSX now just like before I am RC on the top and then CC nav bar here in the render method we simply return the mark-up that we copied from bootstrap we just need to rename class to class name and we're done also we don't need the state here so let's delete it so here's our navigation bar component now let's go back to apt at Jas we don't need this markup anymore instead we want to render our navigation bar so on the top we also don't need the logo let's import nav bar from the components folder slash nav bar and then here we add our nav bar component now below that we should add our main element with the class container and inside this element we're going to add our counters I'm gonna go back to index J s on the top you can see the light for importing the counters is greyed out because we are not using the counters component here so let's cut this from here and paste it in app to j s and finally let's add the counters element inside the main element now you can see here we have a compilation error because of this red underline because we're returning multiple root elements from the render method so we need to wrap them with a react dot fragment so react that fragment and then we close it here okay beautiful back in the browser so here's our new layout we have the navigation bar on the top and below that we have our counters now we want to display the number of counters on the navigation bar here's our componentry one more time earlier we passed the state of the counters component to the counter component via props this is because we have a parent-child relationship between these two components but as you can see there is no parent-child relationship between the counters component and the navbar component so how can we display the total number of counters on our navigation bar well in situations like that when there is no parent-child relationship between two components and you want to keep them in sync you want to share data between them you need to lift the state up so in this case we want to lift the state of the counters component to its parent that is our app component now both the counters and navbar components have the same parent this is where we have this state so we can pass it to all the children using props and that's what we're going to do next so here in counters component this is where we have this state the list of counters as well as the methods that modify or mutate the state such as handle increment handle reset and handle delete we should move this date as well as all the methods that modify the state from this component to its parent that is AB component so I'm gonna select all this code here cut it go back to AB component and paste it right here that was the first step now back in counters component here we have a reference to this that handle reset but this method no longer exists in this class now it's part of its parent so we need to pass it down using props so back in AB component let's look at the render method this is where we have our counters component we want to modify this to raise events such as on reset on delete and on increment so on reset reset this to this that handle reset on increment we set this to this that handle increment and on delete which we set to this that handle delete so these are the three events that are raised by this component and here are the corresponding handlers that belong to the app component now let's go back to counters component so we should change this expression to this the props that on reset because that's the name of the property that we set on the prop object so one more time in app component these are the properties of the prop object right now one more time back in counters component which will also update the reference to handle delete and increment so one more time this the props that on delete and this the props that on increment basically what is happening here is that this counter component raises the delete event and here we are bubbling that event to our parent so we are not handling that event in this component we are simply bubbling it up to the parent of this component and one last change we need to make here since we no longer have the state in this component we need to pass the list of counters via props so we should change this to this the props that counters and also like an app component we should pass the list of counters right here we set this to this that state that counters so now this counters component is a controlled component because it doesn't have any state it simply receives data and methods to modify the data via props so it's entirely controlled by its parent so this is how we lift the state now let's test the application and make sure everything is working so let's increment a couple of these then reset them delete a couple of them beautiful finally you need to display the total number of counters here on the navigation bar so here in app component you're passing our counters to our counters component similarly we can pass this array to our navigation bar component so we can pass either in the counters array or just a total number of counters so the navbar itself doesn't have to do the calculations we can simply give it a number so total counters we set it to this that state that counters that legs or we could take this to the next level and filter only the counters with value greater than 0 so we get counters filter them where counter is greater than zero and then and then we'll get the total number of those counters so save the changes now let's go to navbar component this is where we have the label right after that I want to add a span with a few classes like badge badge - pill and badge - secondary here we render this the props the total counters like this save the changes and back in the browser so currently we have only one counter with value greater than zero let's increment the second counter now the value is updated to two if we delete the first counter the total number of counters is updated accordingly so we lifted up the state from the counters component to its parent which is the app component now we can share this date with the children of this component by our props and with this technique we have multiple components in sync you so if you look at our navbar components we only have a single method here that's the render method we don't have any event handlers here we don't have any helper methods to calculate values we only have a single render method also we don't have any state we're getting all the data via props in situations like this we can convert this component into what we call a stateless functional component so instead of using a class to define this component we can use a function let me show you how to do this so we define a constant call it navbar and set it to an error function like this in the body of this error function we return a react element so basically we take our return statement from here and move it inside of this function so instead of having a class that extends the component class with the render method we simply define a function that returns a react element that's why we call this a stateless functional component that there is nothing wrong with using classes to define components but some developers prefer to use functions when they're dealing with simple stateless components what I approach to choose is pure your personal preference but you see a lot of examples of stateless functional components on the internet that's why I decided to include this in the course now we also have a shortcut for creating these stateless functional components just like we have CC for creating a class component we have SFZ for creating a stateless functional component so this gives us a template for defining a function and also exporting it now we don't need this so delete now one more thing before we finish this here we're referencing this dot props in class components in functional components you need to add props as a parameter here and then remove this react will pass the props object as an argument to this function at runtime here in our navbar component we have a single reference to the props object sometimes when working with a more complex markup we might have multiple references to the props we don't want to repeat props dot props the HUD props that's several times so we can use object destructuring 2d structure this props argument in this particular example we are interested in the total counters property of this object so we can destructure this argument and pick the total counters property first we add parentheses then we use curly braces for object destructuring and then pick the properties we're interested in like total counters with this we can remove props dot and this simplifies our code similarly if you look at the counters component you can see here we have several references to this dot props we can simplify this code by using object destructuring so here in the render method just before the return statement I'm gonna define a constant use object destructuring to pick the properties of the props object we're interested in the first one is on reset so we pick that the second one is counters let's add that here we also need on delete and on increment so on delete and on increment we pick all of these from this dot props now anywhere we have this the props dot we can replace all of those with nothing and this makes our code cleaner our components go through a few phases during their lifecycle the first phase is the mounting phase and this is when an instance of a component is created and inserted into the Dom there are a few special methods that we can add to our components and react will automatically call these methods we refer to these methods as lifecycle hooks so they allow us to hook into certain moments during the lifecycle of a component and do something and the mounting phase we have three lifecycle hooks constructor render and component did mount react will call these methods in order the second lifecycle phase is the update phase and this happens when the state or the props of a component get changed in this phase we have two lifecycle hooks render and component did update so whenever we change the state of a component or give it new props these two methods are called in order and the last phase is the unmounting phase and this is when a component is removed from the Dom such as when we delete a counter these lifecycle hooks you see here are the frequently used ones if you look at the react documentation you will see a few more lifecycle hooks but they are rarely used and that's why I didn't want to confuse you with too much details that you're not going to use that often 90% of the time you're going to use only the lifecycle hooks that I've listed here now let's see these lifecycle hooks in action you so here in the app class first let's look at the mounting phase I'm gonna add a constructor and because we have added a constructor here we need to call the constructor of the parent class using super so here we have a constructor let's do a simple console dot log AB constructor this constructor as you have learned before is called only once when an instance of a class is created this is a great opportunity for initializing the properties in that instance for example one common use case is to set this date based on the props that we receive from the outside for example we can set this that state to this the props dot something so here in the constructor we set this state directly we don't call this the set state in fact if we do that we'll get an error because this method can only be called when a component is rendered and placed in the Dom so if you need to set this state directly you can do so in constructor also note that here we won't have access to these stock drops unless we pass props as a parameter to this constructor and also pass it to the constructor of the base class otherwise this the props will return undefined let me show you so temporarily I'm gonna comment out this line and log this dot props here here in the console you can see our constructor is called and our props object is an empty object but if you forget to add the props to this constructor we won't be able to access it so to recap the constructor is called once and it's the right place to initialize the properties in this class now let's remove this stuff props from here the second lifecycle hooks we're gonna look at is component did mount component did mount this method is called after our component is rendered into the Dom and it's the perfect place to make Ajax calls to get data from the server so we can do an ajax call and then call the set state with new data for example in our feed the application later in the future we're going to get the list of movies from the server and the pass that list to our set state method something like this for now we don't have to worry about this let's do a simple console dot log app mount it and the third life circle hook and the mounting face we're going to look at is the render method which you have seen before let's just add a console that log AB rendered now back in the console look at the order in which these methods are called first we have the constructor then the component is rendered which basically returns a react element that represents our virtual Dom now react gets that virtual Dom and render it in the actual browser Dom and then our component is mounted so when a component is mounted that means that component is in the Dom and once again this is the right place to make Ajax calls and get the data from the server now one thing you need to know about the rendered method is that when a component is rendered all is children are also rendered and recursively let me show you so here in our app component look at our render method here we have a nav bar and a counters component so let's go to our nav bar component here we have a stateless functional component in the body of this function before our return statement let's do a consult blog and display nav bar rendered now one thing you need to notice here is that you cannot use lifecycle hooks in stateless functional components because here we have a single function that returns the output of this component so if you need to use lifecycle hooks you can only use class components now let's go to our counters component once again here in the render method I want to add a console dot log with a message like counters rendered and the last part let's go to our counter component do the same here in the render method and change the message to counter render now let's go back to the console as you can see first the constructor of our app component is called and then our app component and all is children are rendered recursively so we have app navbar counters and for instances of the counter component and finally at this point our app is mounted and is in the done so this is our mounting phase now let's look at the update phase so that phase happens whenever the state or props of a component changes as an example let's look at our increment button so let's go back to our AB component here's our handle increment event handler in this method we're updating the state of AB component so this will schedule a call to the render method so our app is going to be rendered which means all is children are going to be rendered as well let's see this in action so back in the console I'm going to clear the console and click the increment button so once again you can see our entire component tree is rendered now I just need to clarify that when I say our entire component tree is rendered that doesn't mean that the entire DOM is of data when a component is rendered we basically get a react element so that is updating our virtual Dom react will then look at the virtual Dom it also has a copy of the old virtual Dom that's why we should not update the state directly so we can have two different object references in memory we have the old virtual Dom as well as the new virtual Dom they only react we'll figure out what is changed and based on that it will update the real dumb accordingly so here even though we have several counters when I click the increment button only this span is updated nothing else will be affected let me show you so if I go to the LMS tab and select this element here I'm gonna click the increment button and I want you to look at this span here so increment C it gets highlighted because it's content is updated however if I select another counter and click the increment button of the first counter look nothing is happening here so there is no update on this part of the Dom now back in our counter component I'm gonna add another life circle hook here component did update this method is called after a component is updated which means we have new state or new props so we can compare this new state with the old state or the new props with the old props and if there is a change we can make an AJAX request to get new data from the server if there are no changes perhaps we don't want to make an additional ajax request this is an optimization technique so let me show you here we add a couple parameters previous props and previous state let's do a consult that log of previous props as well as another console in the log to show the previous state previous state now save the changes back in the console I'm gonna clear the console and click the increment button of the first counter note that the value is currently 4 so click look at the console so ignore all the rendered messages look at the first previous props so this is the props object that we're passing to this counter component you can see the value of the counter was previously 4 but now it's 5 so we can write code like this if previous props that counter that value is different from this the props that counter that value then perhaps we're gonna do an ajax call and get new data from the server however if the value is not changed per house we don't want to make an additional call to the server of course this does not make sense in the context of our counter example but what I want you to take away here is that with this method component in update we can decide whether we should make an AJAX call to get new data based on the changes in props and state objects now finally let's look at the unmount face so in this face we have one life cycle hook that is component will unmount so this method is called just before a component is removed from the Dom let's do a consult that log of counter unmount now back in the browser I'm gonna clear the console again now note that when I delete this first counter we will see the unmount message on the console see what's going on here as a result of deleting a counter the state of AB component is changed so our entire component tree is rear-ended we have app nav bar counters as well as three counter components so with this we have a new virtual Dom that has one less counter react we'll compare this virtual Dom with the old one it figures out that one of our counters is removed so then it will call component will unmount before removing this counter from the Dom and this gives us an opportunity to do any kind of cleanup so if you have sort of timers or listeners we can clean those up before this component is removed from the dump otherwise we'll end up with memory leaks in this section you learn a lot about composing components more specifically you learned how to use props to pass data to your components as well as raise and handle events you learn about lifting the state and with this technique we could have multiple components that share the same data and we're in sync you also learn about functional components and lifecycle hooks in the next section we're going to extend our via application and add pagination sorting and searching so I will see you in the next section [Music] you made it this far and you seem to be very enthusiastic about learning react I hope you have learned a lot in this crash course so please support me by liking this video and sharing it with others if you want to learn more from me I've got a comprehensive react course that's the continuation of this crash course in that course we'll talk about pagination searching sorting calling backend services authentication and authorization deployment and more as I told you before the link to my course is in the video description thank you so much and have a great day you
Info
Channel: Programming with Mosh
Views: 3,927,341
Rating: 4.9396272 out of 5
Keywords: react js, react tutorial, learn react, react course, reactjs tutorial, react crash course, react js tutorial, reactjs course, react tutorial for beginners, react.js, reactjs tutorial for beginners, reactJS, react, learn reactjs, tutorial, javascript, crash course, programming with mosh, code with mosh, web development, mosh hamedani, learn react js
Id: Ke90Tje7VS0
Channel Id: undefined
Length: 145min 27sec (8727 seconds)
Published: Mon Jul 16 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.