Beginner's Guide to React w/ Hooks (2020) Free Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone it's colt i hope you're all doing well today i'm here with a intro to react course a youtube crash course using all the latest in react specifically react hooks this is somewhere between two and three hours of content i haven't actually finished editing it officially so i'm not sure but it's pretty thorough it's not going to cover everything you need to know i mean i have a react course that's 30 something hours there's a lot that we could talk about but i think it's going to be a good intro now i struggled for ages to get this video out you can see uh last week i had a react one hour video i was gonna make and then i re-recorded it react one hour real and then react youtube actual real and then react youtube course for real i've redid this over and over and over i just wasn't happy with it i was trying to do something shorter but i found myself just constantly saying things like ah don't worry about that for now you can learn more about that later and i just don't like doing that so it's longer than i intended we cover a lot of topics for example what is react how does it compare to angular what are react hooks class versus functional components the basics of jsx props and states the use state hook create react app how to update and mutate or avoid mutating state properly state as props which is a common design pattern styling react the use effect hook there's a ton of stuff so we've got a lot to talk about and just before i do that i want to remind you all if you're not familiar with this of my online bootcamp that i launched earlier this year it's a self-paced course that guarantees you a software engineering job or you get your money back this thing has been a true labor of love for me uh it's far more content than i've ever recorded in pretty much all my courses combined uh there i am by the way and my cute cats the curriculum is massive uh with the projects and the exercises it's over 800 hours of work for you you've got video calls and your mentor a big community of students live chat you meet with career coaches we review your portfolio we review projects you get code reviews critiques on your code mock interviews and of course the big thing the money back guarantee if you don't get a job so take a look at the link in the description if you are considering changing careers or if you are in need of a new career i also have a 500 discount or scholarship whatever you want to call it that you can find in the description as well all right so enough of that let's get back to react let's begin with an overview of what react is and how it compares to other kind of similar tools like angular so react according to the documentation the official home page is a javascript library for building user interfaces a couple things of note uh first of all the term library other tools that people would use in lieu of react that kind of do the same they have similar goals include vue and angular there's also ember knockout there's a million though the most popular right now are react angular and view angular refers to itself as a framework view does the same they don't use the term library now that's not just semantics although some people do call react a lightweight framework or a small framework the difference is that a framework generally is more controlling broader in scope comes with more out of the box a library is something that you tend to be able to plug and play you can add it into an application you don't have to work within the confines of a framework so neither term is inherently good or bad but it's important to note as we start out here that react is pretty lightweight compared to something like angular learning angular can be a little bit challenging because of just all of the things it comes with you've got routing built in and animations a whole bunch of different tools that come with angular out of the box compared to something like react which is pretty minimal but if you incorporate a lot of these standard react tools or add-ons that are separate libraries separate tools that you install and use it starts to basically become a framework but react on its own is pretty small learning it is not terribly difficult learning the basics that doesn't mean that it's easy to master it just means that there's only a couple methods a couple of concepts you really have to understand in order to get react to summarize all of that its scope is much narrower than something like angular alright so before we talk more about what react does i should just mention that it was initially developed in-house at facebook for internal use and then eventually it was open sourced and these days it's still used by facebook it's used by many many large companies netflix instagram facebook obviously airbnb tons of applications out there instacarts new york times lots of websites and if you're here watching this video you probably already know this react is incredibly popular these days in 2020 it is super in demand tons and tons of job opportunities said list react anyway these days it has a huge community around it it's a good thing to know all right so let's talk more about what react actually does and what it helps with essentially react helps us synchronize what a user sees what the actual interface is displaying with underlying data typically what we would call our application state so without a tool like react if we're just doing vanilla javascript suppose we're building a simple game this is something i found on codepen it's a hangman game there is underlying data we have variables the categories the chosen category if you're getting a hint or not the word itself your guess guesses which spelled incorrectly the number of lives a counter these are all important pieces of data that change at least a lot of them change behind the scenes uh as i make a guess let's see premier league football teams um our arsenal maybe would fit there so we have 10 lives and then as i guess i'll guess a and uh let's see swansea maybe let's see uh s where are you okay i think that's what it is but i'm gonna make an incorrect guess on purpose so how about an r and you'll see my lives goes down there so i'm clicking there's some code that's running behind the scenes that is updating the number of lives by selecting this element checking the number of lives in a variable subtracting one from it if i guess incorrectly and then updating what we see here that process is done manually select something change the inner html select these elements and add a class to them probably after i click on them the point is that there is effort that goes into keeping what i see here in sync with the data behind the scenes or here's another example it happens to be a game 2048 it's someone else's code pen as i move with the arrow keys my score is going to change so there are calculations done based off of some underlying array that is storing the game board things are combined numbers are changing classes and colors are changing that's all happening based off of some underlying source of truth the actual game board is kept in an array in this code pen and then when i move and combine certain squares i am adding to the score and that's being reflected here so the current score is being updated there's dom selecting going on there's manipulation inner html text content all of that stuff and this can get kind of crazy on a large application for example something like home depot's website which is built with react let's take a look at a shopping cart just the shopping cart i've got i don't know what 10 items in here and each item has a quantity i can remove it i can save for later i can change the shipping method all of this is stored somewhere in javascript the number of items the price for each item the subtotal for each item the overall subtotal and as i change something let's say i want i don't know eight of these you'll see that the subtotal here updates if i put eight right there it updates live then this updates down here my new total updates if i changed my shipping methods to be free pickup from a store then we would see the shipping price change down here sales tax will be calculated long story short this is a pretty simple page on home depot but just keeping everything in sync making sure that the correct quantities and prices and subtotals are all updating live would involve a lot of selecting and updating inner html and inner text and changing the values manually if we weren't using a tool like react so that's where react comes in react helps us efficiently update uh and render just the right things when our data changes so we can tell react here i would like you to display the subtotal for this item or here i'd like you to display the subtotal for the entire cart and whenever that value changes i want you to automatically update it here so i don't have to go in and select this element i don't have to set the inner html and the way that we organize all of this is through components so the component is really the the one building block in react it's the one central concept that you have to understand to in order to use react really all you're doing is writing a bunch of components components are just reusable self-contained modular however you want to put it pieces of code generally html with some css and javascript logic combined into this reusable component you can kind of think of them as fancy customized html elements you can come up with your own name we can have a navbar component we could have a shopping cart item component or the entire shopping cart component within that one of these items we could have a shipping selector component and within that we could have a shipping method button component or something like that so that's what react helps us do it helps us define these components and use them and compose them together to make a large application so i like to show this diagram when i'm teaching react there's this idea of the separation of concerns where you're supposed to keep your javascript separate from your css and your html separate from the other two with react we are separating by concern just from a different perspective we're going to make our components using some html some css and some javascript and they're separated by functionality or by thing so we can make a date picker component a modal component a shopping cart item component we could have a rating component a five star rating component where it displays some number of stars out of five but we could also make it interactive so i could change that rating so there's javascript logic there's css maybe each uh value has a different color so a one out of five stars rating is red and a five out of five star rating is gold or something so here's an example of that from a code pen one that i didn't write there is a rating component this is a resume a fake resume and this right here every one of these five star little things is an instance of the same component the same component type but they have different values and that's crucial to be able to make these components repeatable or reusable but not identical they follow the same pattern every one of them has five possible stars every one of them has a hover effect as i move across them every one of them will change when i click i can set a new star rating but they're not all identical they all have a unique value a certain number of stars anyway that's a very simple example here's a more complex realistic example this is from the new york times webpage at the very bottom there's a lot of react components on the page but i'm just going to focus on this right here this more in science this is a science related article i'm reading and there's this little uh box down here more in science now i have the react dev tools installed something we'll cover later on but if i open them up here and go to react oops i want components here and i select this right here you'll see that there's a component called more in and this more in component accepts different properties for example it accepts a section name which is set to science but i could actually change that and i could say more in how about business and you'll see that that change is reflected here so whatever this property the section name is is used to construct the actual markup we see and then of course there's different information in here different images and different i think they're actually called a more in item so that's one component here here's another more in item and they make up the entire more in component and within each more in item there's a recirculation item there is a content link that's another component there's an image with credit component there's a lazy image component so lots of tiny pieces put together to build a larger piece and that's only one small part of the entire page and then if we look at this other article it's in the travel section and i scroll down here is a different more in component same overall component but different data and different properties so we see something different but it's the same pattern that's been defined so that's what reacts helps us do it helps us define these components these reusable pieces of logic and ui information combined put together with a nice bow on top that we can then instantiate across our application all right so now we're going to start talking more about the actual code and soon we'll be writing some react code so the way that we define these components has changed over the years there are two main ways we can write a react component one is using a class and another is using a function so two ways of defining a component and until recently they didn't have the same set of features so a class component was way more commonly used uh class components had access to all of the important react features and function components were much simpler and they didn't have access to they missed out on some of the more useful react features so we would use class components and then whenever it made sense we could use a simple function component just to make things shorter however that has changed with the advent of react hooks react hooks allow us to write function components that include all of the functionality all of the features that we used to have to write a class component to have access to basically it makes function components the de facto way of writing components in react it is a newer feature so there are lots and lots of code bases that still use class components it will take a while for everybody to migrate over but the way forward for react is through functional components using react hooks so just to give you a demonstration don't worry about the actual code here but here is a class-based component you can see the class keyword so this is how we used to write this it's a counter component a very simple component with a class and it's kind of long and if we look at the now equivalent function based component that uses react hooks it's way way shorter and way easier to read so it's shorter which is obviously important and easier to read is always nice but there are other benefits of hooks there are reasons a lot of long-time react developers are very excited about hooks so yes shorter components but also functional components and react hooks make it much much easier to share code between components we can share logic which we used to not be able to do or at least not be able to do easily hooks are also easier to learn in a lot of ways but also potentially harder to master so hooks are great people are very excited about them however just a word of warning the documentation is still catching up so there are lots of tutorials and there are docs for react hooks but if we look at the home page here it's still using class based components you can see there's a class here we've got class here and the main tutorial if you do follow this tutorial is all class based as well so that's not necessarily a bad thing but that will eventually change to reflect react hooks but there are docs on react hooks it's a separate section as you can see here anyway hooks is a pretty massive shift in the way that we write react so it will take a while for everything to catch up but this video will help you get started so let's actually do that let's start talking about actual code so let's start writing our very first most basic component remember we're writing a function based component we're using react hooks here but we're going to start with just a very very basic functional component which is really just a function that returns some content that we can render into the dom so to begin i'm going to be doing this in a code pen just to show you at least at the very first part of this video that you can write react code you can use react with a standalone html file you don't have to have a whole bunch of tools and you might be familiar with something called create react app which we'll be playing around with in just a bit but you don't have to use any of this stuff you don't need your command line you don't need to use webpack and a whole bunch of other things that come with create react app but it is very useful so to start i'm going to just keep things simple in a code pen it's a completely empty code pen i've collapsed the css window because we're not going to bother with that for now so we're writing a functional component which is just a function that returns content we can write a function declaration so function i'm going to name this component how about just dog to start and it's conventional to have a capital d or capital letter for your component name to indicate that it's a component not just a regular old function it's also pretty common to do a arrow function so const dog equals an arrow function and that is definitely more common to see in react okay so i'm going to return some content from here it's going to be a very simple component it's not even going to return anything fancy just a string that says woof i am a dog i don't know why this part's capitalized and this part isn't but whatever so that is just a regular function it has nothing to do with react at this point i don't even have react involved with this code pen so i'm now going to go and add react as a dependency and if i'm doing this using codepen i can just search for react here on the javascript tab click save and close i click the little gear there and added react you can also obviously add a script you can download react if you're doing this on your own with an html file add a script tag you can use a cdn so i have react here and the next thing i need to do is actually create a place in my html where i'm going to render my component so with react we create components and just like any function just defining it doesn't do anything i need to call this function but i'm not just going to execute dog i'll just be returning a string what i want to do is render dog and to do that i need a place to render it and what you'll frequently see is a div with the id of root this is the one div on our page where we will inject our content from react you don't have to name it that but that's really common to see then this part's a little annoying but in order to actually render something into the dom we actually have to include a second script so we have to include react and then our second script is called react dom react dom is very simple and there's really just one method that we're concerned with it's called render so render is how we render a react element into the dom in the supplied container so there are two things we pass in a react component and a container and our container as we just discussed is going to be this div and the react element is going to be an instance of our dog component so to use react dom i actually have to go and add that as a separate dependency so i'm going to search for react so number two right there react dom i'm gonna get rid of that okay so i now have those two dependencies in there react and react dom then at the bottom here i'm going to render my dog component into this div with the idea of root and the way we do that is react dom all capital for dom dot render is that method i just showed you on the docs and then the first argument is our component and we don't just write dog like this we don't execute it as a function we're going to write this right here we'll talk more about this momentarily it looks like an html element we're using angle brackets here and then i'm going to tell it where to render i want it to render in this div that has the id of roots so i need to select it i could use a query selector i could use get element by id i just need to select that div and then close my parentheses so i could put this in a variable if i wanted to but it's really common just to have this inline it's something you do once we render a component one time into that div but there's a problem this right here is not valid javascript it says syntax error unexpected token less than i can't write a less than sign in this context in javascript of course i can use it as an operator 1 less than 2 but i can't use it like this right here so this is some special syntax that is used commonly with react we're going to talk about it something called jsx in order for it to work i also have to include babel so babel is going to transpile this code which is not real javascript into real javascript but we'll get there and now you can see my component is rendering here we get that return value woof i am a dog it is being rendered inside of that div now of course this seems like a lot of work just to get woof i am a dog to show up inside of a div and it is but that's not really how we use react in the real world but this is the basic mechanic we define a function if we're writing functional components it returns something and then we render that component or an instance of that component into some element in our html commonly a div with the id of root all right so let's talk about this syntax right here again not valid javascript we needed to get babel in there to transpile it to make it valid what it is is something called jsx jsx is not mandatory to use with react but i don't know if i've really seen anyone not use it outside of the documentation when it tells you it is not mandatory and they show a demo of how you don't have to use it outside of that i don't think i've actually seen anyone deliberately forego the use of jsx so it stands for javascript syntax extension that's kind of what it is an extension to regular syntax in javascript and it allows us to write what looks like html directly inside of javascript so you can see an example of that right here i've got a component and i'm returning a div with two paragraphs inside so not only is that not valid syntax the angle brackets instead of javascript also html is not a thing inside of javascript if i want to create a div through javascript i need to do document dot create elements and all of that stuff i have to append it i don't need to do any of that if i'm using react in jsx instead i can write what looks like html i can return that from a component and whatever i return here will actually be created as elements in the dom technically these create what are called react elements they're not exactly the same thing as a standard dom element it's a react wrapper it doesn't really matter at this point when we're just starting out but what does matter is the fact that this is not standard javascript and you must have babel if you want to be able to write jsx so again we added that in here with codepen it's super easy if you're doing this locally on your own machine just in a text editor like vs code make sure you get a cdn for babel or you download it but shortly we'll be using create react app which includes babel all right so instead of returning wolf i'm a dog let's return how about an h1 and this h1 will say i am dog and i'll close my h1 and there we go i'm getting an h1 and h1 is actually being rendered inside of this div there are some important rules to understand with jsx first of all let's say that i want my component to actually render an h1 and i want an h2 down below it that says i don't know woof woof so i want more than one element that makes sense most components are more than one html element so i'm going to try adding an h2 after this so h2 woof woof and close my h2 tag just like that but nothing's showing up why not well rule number one with jsx is that you can only return one element from a given component we cannot have adjacent elements at least not without some parents around them so these two are adjacent elements they're siblings there's no one thing wrapping them so what we used to do and what you can still do is return a div or some random well it's not random but some parent that exists just to group our content together and now things work fine but if you don't want an extra div there's this other option called a react fragment which does not actually result in any new markup so it's not going to make a div or it's not going to make some other element in the dom it solely exists to group our content together but it doesn't really matter for now so we can do this what you'll also see is the use of parentheses sometimes so if you wanted this to all be on a new line you could do something like this return this whole thing here and you can even indent this if you want you can format this however you would format your html but remember this is not actually html babel will turn each one of these elements into a function call that creates a dom element for us so that's rule number one here you can return one jsx element from a given component it can have as many sub or nested elements as you want but there can only be one parent next rule number two some elements in html do not have a closing tag a simple one would be something like an hr a horizontal rule this is how we write that in html but i'm not getting anything here my h1 doesn't show up my h2 doesn't show up and that's because of rule number two in jsx if you have a element that does not have a separate closing tag you have to add the slash at the end that trailing slash to close that element and there's my horizontal rule this is also why we had to add the slash here to render our dog if i just did that it's not going to work for me okay so two main rules there are others but those are the two important ones return one element from a component one parent element and any elements that don't have an explicit closing tag must have that slash even if you don't need it in html so commonly uh this comes up with things like images so you would have some image source i'm just making that up in order for this to be valid in jsx you need that slash there and this has to do with how babel is parsing this code how it's able to determine where an element begins and ends it needs that slash there so that it knows oh this is the end of the image okay so at this point our component dog is static it's the exact same thing every single time there's nothing dynamic nothing changing about the content here it's always i am dog woof thanks to jsx though we can actually embed javascript expressions directly inside of our jsx elements and the syntax to do this involves the curly braces so if we have an opening and a closing curly brace anywhere in jsx the contents between the opening and closing curly brace will be evaluated as javascript so i could do something like one plus five here and you'll see that we end up with six rendered to the dom so this will be run first we get six and then that number or whatever comes out of those curly braces will be embedded directly in our markup so why don't we do a really simple example let's make a component that is just a random number generator so const random num equals a new function and before we return our jsx stuff get rid of that extra period there why don't we pick a random number so i'm going to just make a variable up here constnum equals math.random and then let's multiply that by maybe 10 and that's not going to be a whole number it will be a decimal so we can floor that but then why don't we return maybe just an h1 here that says your number is and then we can embed instead of curly braces the value of num whatever that number is and then close my h1 and i'm not going to see anything aside from my dog because i need to render a random num to this div so i can actually only render one thing one top level element to this div using reactdom.render so for now i'm just going to replace dog with random num and what do we get oh such a lovely number and i refresh the page i get a new random number i refresh again a different random number so a simple component here yes it's just a random number generator but we are embedding a variable directly inside of an element and this is really really common if you think of some of the examples that i've pointed out earlier for example one of these cart items i'm not sure exactly what they're called but we'll call it a cart item and there are different pieces of information every single one has a title or a name but they have different titles or names so in this component whatever it's returning let's just say this is an i don't know an h3 or something in h4 it has curly braces with some variable being rendered here same thing for the model number same thing for the price these all follow the same pattern so in our example we did a very simple just a num that's being displayed but we could have a much larger component that has 10 20 50 different pieces that are dynamically rendered based upon some value some javascript expression and we're not limited just to adding variables in like i did here i mean we saw that we can do math one plus five or something but we can also add conditional logic so instead of just returning an h1 maybe if this number is larger than five i would like to also have let's say an h2 that i don't know it says something like that's a large number uh or congratulations or who knows i just want to display something if number num is greater than 5. so i could start by just writing the content that i want to display now what's the problem with me doing this if i just add an h2 here that says big number and then i close it why is nothing showing up well remember that rule with jsx we cannot return two adjacent elements there must be one element so i'm gonna wrap them together in probably a div or a fragment which i showed you earlier i'm not sure which one probably just a div to keep it simple in case some of you skipped ahead and you didn't see what fragments are so i'll indent that just to keep my sanity okay so now we're always displaying big number which is not what i want i want to dynamically display it only when num is actually greater than five and there are multiple ways of doing this i'm just going to show you probably two there are blog articles uh about seven different ways of adding conditional rendering in your react components but here are two options first off if i wanted to have big number as one option and then as the second option we'll go with small number of course they're just showing together right now if i wanted one or the other i could make a separate variable i can save these jsx elements into a variable remember that after babel does its thing and these elements are transpiled they're basically turned into function calls and i can save that return value i can save one of these to a variable so up here i can do it outside of the return statement i could do something like const message equals and to start i could just hard code it as big number just like that and then down here i can render that variable i'll just do it right there message so that variable is message and it's actually going to be an h2 a jsx element added right there it's the same thing but what i could do is actually have a little conditional statement that says if num greater than 5 then i can set message to be big number and then i could add an else and set message to be small number so that's one option here i render message there and i run into a lovely scoping issue because i'm using constant a block here so i'm gonna do something like this let message and i get big number because numb was 6.2 but if i refresh this page well still big number try again big number big number come on give me a small number there we go small number so that's one option for doing this more commonly you'll actually see this done in line so if you're just doing something simple like changing the text big number versus small number i could add an h2 right here and i can start with big number small number but then i can use curly braces to dynamically set the inner text inside of this h2 element based off of whether num is greater than 5 i can use the ternary operator in javascript so this is just standard javascript we're just embedding it inside of those curly braces so is num greater than 5 question mark if that's the case we need to decide what will be rendered in this h2 so i'm going to just add a string and it will be big number and then my else is a colon small number i guess technically i could move number out and then just do big versus small and i guess i'll do that just to simplify that a bit i'll add a space here and then number and there we go so we do need quotes here because we're inside of javascript these curly braces indicate that we're actually in the land of javascript and it would be invalid to have big without quotes okay so this is really common to have a ternary operator embedded inside of some jsx and now we have a simple dynamic component where we have a number that's being rendered dynamically it changes it's a random number and we have our message small number versus big number which changes depending on the actual random number okay so just simple stuff at this point i know nothing crazy but these are fundamental concepts in react returning jsx and then having javascript embedded inside of our jsx sometimes it's just a variable that we're embedding other times we have expressions like we have here and later on we'll see that we can also add loops so if we have an array of elements and i want to loop over each one and do something i want to render something for example i want to loop over every item in my cart array if there's an underlying cart array with 10 items or however many items and for each one i want to render one of these components we would need a loop so we'll see how to do that later for now i'd like to shift a little bit and talk about our application structure we've just been rendering a single component at a time but in these examples i've shown you i hate to go back to this home depot website but there's a bunch of components on the page at once or this new york times example there are probably dozens of different components on the page all at once i mean right here we've got six of one component type and they're nested in some component we talked about called a more in component these are more in items there's probably a sidebar or a most popular component and then a most popular item component all of these are rendered on the same page at once how does that work well we need to change our structure instead of rendering a single component randomnum into this application or into this div rather we're still going to render a single component but we're going to make a new component that we're going to call app and this is conventional doesn't have to be called app but basically we make one component that we render and that component can then itself render as many other components as needed so i can define that here const app again just a conventional name to be your top level components and we'll return a div that itself renders a random num component so i'll put that right there and then i'm going to render my app here so now i'm never going to change this line i mean i can but typically we don't touch this if i want to change what's actually being rendered in my application i update what my app is rendering so inside i return a div with a random num but i could add two random nums and remember i do need that closing slash and this has to match the exact name of my components and there we go three separate instances of that component of course they all happen to be small numbers let's see if we get a mix here big and small okay so this is big big big and here's a small number okay so i could also throw in a dog if i wanted to i have that component defined this is really the benefit of having this separate app component or some top level component that we render i can render whatever else i want inside of here and i can render other components inside of something like randomnum i could render a dog component it doesn't really make sense but i can have you know this app component that renders a random num random num can render a random num button and randomnum button can render something else if we go back to my slides for a moment this last point here composition is really important we can combine multiple components to form complex apps all right so yes it's possible to use react with a single html file a single javascript file and not have to rely on any fancy tools yes this is a code pen but this could also be just an index html with a separate script now if we start working on large react applications we might have 50 or 60 or maybe 100 different components and there might be a separate style sheet for each component there might be separate test files all of a sudden uh things get kind of crazy we have thousands of different files man that might be an exaggeration we have hundreds of files on large apps and uh we need to organize them that's one thing but also what's really important is to make sure our actual components load in the correct order in this simple example we have three different components and our app depends on random num being loaded or the browser knowing about randomnum and dog so if we were to put these in separate files we would have to make sure that dog came before app and we'd need to make sure that randomnum came before app now if you extrapolate that to a much larger application with nested components maybe going three four five ten levels deep it becomes really tricky to order everything correctly to make sure all of your scripts are included correctly it's just obnoxious to manage the dependencies and to structure your application so we don't use a code pen for a typical react application what a lot of people use these days is something called create react app this is another tool originally put out by facebook it's basically a command line command that you can run to very quickly get up and running with a react setup so it gives you react it gives you some testing tools for react it gives you webpack to help you bundle your code together to load things in the correct order to manage dependencies it comes with babel and a bunch of other tools all set up for you and all you have to do to install it if you have npm a recent version of npm you can run this command from your command line uh if i just copy that line head over to my terminal i paste that in it takes a little bit okay so that finished up it makes me a new folder the name of the app was my app just from the command i ran and if we look inside that folder there are a couple of files and folders made for me i'm going to open this up just to show you very quickly in a text editor all right so here we go there's a couple of files made for us there's an index html and it has a root div and then there's a source directory this is where we actually write all of our components and there is one component pre-written for me the app component and if i go to the index.js file you'll see that this line reactdom.render is going to render an app component don't worry about this react.strict mode for now it renders the app component into the div with the id of root now there's a bunch of other stuff going on here we don't really have time to get into it fortunately you don't have to worry about it at this point in order to use create react app we break things up into separate files typically one component per file at the top of each file for a component we will import react from react and that's a way of telling webpack that this is a component that depends on react we need to make sure react loads first and then we export our component in this case it's the app component from the file which typically has the exact same name as the component and i'll show you this process of making a new component and going through that but i'll begin by starting up the server so it's as simple as npm start inside of the directory that create react app made for me and this is what i see in the browser it automatically opens localhost 3000 it's a live server so if i change something like i'll change my app component you'll see that there's quite a bit of markup here already well it's not quite a bit but there's a couple of things and there are some default styles in there but i can get rid of all this if i want to and make my app component just an h1 that says hello from app and i'll save and this will refresh automatically and i'm now seeing what my app component looks like and that's really just one nice part of create react app there are many many features that make our life a lot easier if you actually look at the node modules directory these are all of the dependencies that we get or that have to be installed in order for create react app to work which is why it kind of takes a while and a lot of them are nested dependencies uh they're dependencies of dependencies and so on but the point stands it does a lot for us and it depends on a lot of individual node packages so to make our own components here it's very similar we still write a function as a component you can do class components too but we'll write a functional component we return jsx and then we will export that component from our file and import any dependencies so i'll show you an example i'll make a new file in the source directory and let's make a component here just a very simple one let's go with a navbar component we'll call it navbar.js and then in here i'll define my component which will be a functional component this time i won't use an arrow function just to mix it up function navbar and it's going to be incredibly simple we'll return how about a nav element which has uh maybe a ul inside with a couple of lis and the first li i'm not even going to bother adding real links i'll just add home contact and about now i need to do a couple of things in order to make create react app happy specifically to make eslint happy which comes with create react app it helps us catch bugs and fix issues or at least alert us to issues with our react code and it tells us react must be in scope when using jsx eslint we need to make sure to import react from react so i'm going to go over to my nav bar and do just that we'll do this at the top of every single component we write if you're using create react app and then at the bottom here i'm going to export my component and usually this is a default export navbar if you're not familiar with this module syntax don't worry about it it just allows us to share code between files i have a video on it not in the context of react specifically i have a whole course on youtube as well on webpack okay so if i want to render my navbar at the moment nothing is going to happen because i'm never including the navbar in my app component the app component is the only component that is rendered to the actual dom it's rendered using react-dom just like we did in our code pen but now it's done in a separate file we didn't make this file we're working in a large structure but it's the same mechanism behind the scenes reactdom.render into that root div so in my app component i can render a navbar if i wanted to that's the name of my component remember i need to close that that forward slash but we're going to have a problem here there's a couple of problems first of all it tells me thanks to eslint adjacent jsx elements must be wrapped in an enclosing tag so i have to have some sort of tag we've already seen this that wraps around my content if i'm going to have multiple elements and then we still have another problem navbar is not defined so just like i had to import react i need to import any components any files that i'm planning on using in this one file so i need to import navbar so i'm going to do that now import navbar from dot slash navbar dot slash is just a reference to the current folder in the same folder we're looking for the navbar file and we have to make sure we're exporting navbar and that's all good we don't need this logo this is uh the default logo that we saw the spinning react logo from the default configuration for create react app so we can get rid of that now i think i'm going to put my nav bar above the h1 it's going to be hideous and there you go you can see my navbar component is rendering here so that's the process for making a new component ignoring the actual content of the component it's the process we follow in create react app you make a new file name it the same as your component you don't have to but that's conventional make that component the default export import react and any other components that you depend on and you should be good to go now let me show you the same exact thing briefly in the browser if you don't want to use create react app if you don't have node installed or you don't want to deal with the command line or you just want something quick and easy you can use something called code sandbox it's an amazing tool in the browser it's kind of like kind of a code pen on steroids maybe that's unfair to codepen it allows us to create a node environment in the browser it's an instant ide so all you need to do if you want to follow along using code sandbox is click create sandbox and then select the react template it will take a moment and then you'll see something like this right here so this folder structure is pretty similar right we've got public and source public has our index html source has an app.js already written yeah the actual message the default page and component is a little bit different but there's already an app written for us there's an index.js which is rendering our app component into the root element document.getelementbyid which is on index html and over here we can see the result of our server running but for the purposes of this video it's exactly the same so if you wanted to make a new component create file give it some name how about cat.js and that's my component here i'll save that just using a shortcut i use command s here in my app.js i now can import that component import cat from dot slash cat close my quote there and then render a cat how about just right there so same exact workflow you can see meow showing up it's in the browser i didn't have to actually install anything on my machine this is one option for you and this is how i'll be sharing the code from this video but feel free to use either create react app is definitely what i would recommend if you are serious about react but if you're just following along with this and you want something quick and easy use code sandbox now we're going to move on to one of the most important really essential concepts in react components which is something called props so far our components are not configurable we can't pass information into them to alter how they behave if we go back to this new york times thing one more time there's tons of components but this component here it's called a more in component it renders a bunch of more in items it changes based off of the category or the section of the news more in science versus more in travel as we saw there's more in business more in politics so it's one component but it accepts a bunch of things including the type or the category it also accepts a whole bunch of other stuff we're not going to talk about so how would we make that work we need to use something called props props are just a fancy way of saying arguments that are passed into a component so the way that we do this is when we render a component we can pass props in just like we would pass in attributes to an html element so just like with an image i can set a source attribute or on a div or any element i could add an id attribute so id equals and then quotes i can do the same thing with one of my components so why don't we make a component that would make sense to pass something into i'll make a component called greeter very simple still standard intro to react stuff i know it's kind of boring so we'll do an import react from react same thing we always do and then i'll define my component function greeter and what i want greeter to do is accept a name of the person we're greeting and then we'll return some sort of i guess just an h1 maybe that actually has a name showing up so hi there comma and then your name but your name will actually go there so we're going to export default greeter same thing if you're following along with code sandbox same process just doing it in the browser but you make a new file you need to export default import react and then in our app or in some other component i could render a greeter inside of my navbar but i'm not going to i'm going to do it in my app i need to import greeter from dot slash greeter and then i'll render one here greeter just like that and hopefully we should see hi there your name so what i want to do is pass in an actual name so i can add a property here a prop prop stands for properties short for properties i'll add in one called name name equals and then i can add in whatever i want inside of those quotes how about karen just like that now that's not going to do anything on its own it's going to pass name of karen to my component greeter but we're never using name so in the component itself we need to make sure that we are accepting props they will be passed as an argument to this function so i'll name this parameter props i could name it anything p data but it's conventional to go with props and this will be an object that contains the properties that have been passed in so name equals karen we should have a name prop called karen and i'm going to render that right here with my curly braces props dot name whoa autocomplete killing me there props dot name refresh this page or i don't even need to refresh it automatically does thank you create react app hi there karen let's do one more example i'll make another greeter but this one will have name of karen how about uh tammy and there you go we now have a configurable component so we have the tools in order to make this one little piece more in travel more in business more in food yes there's a lot more to this component but we can make that one little piece where you can configure the section or the category now we can have multiple so we could have name equals karen and then maybe age so age let's just pass in age of 62 and we'll do an age here as well age equals 27 and i don't have to use age i can just pass it in and not use it in this component it's just like passing in an argument to a function in javascript that doesn't accept that argument or doesn't care for it it will just be ignored but i also have access to it on this props object i'll use a fragment here instead of a div just for variety's sake remember this is just a basically a placeholder that allows us to group multiple elements together without having to add a div or some other element that's actually added to the dom so below this h1 why don't i add maybe a paragraph that says you are and then props dot age years old okay and then refresh here and we see hi there karen you are 62 years old hi there tammy you are 27 years old so we have two props being passed age and name another really common pattern with functional components is not to have a single parameter called props but rather to destructure the individual pieces you want instead of props.name and props.age props is just an object and i can destructure if i want age and name i'll just grab those two pieces name and age just like that and now i can just reference name and age if you're unfamiliar with destructuring i have a video on that we shouldn't see any change here now if i leave off a prop if i make how about i leave off age here for greeter what do you think will happen i'll hop over here and we just get you are blank years old what happens just like any argument that is left off to a function is that the value will be set to undefined so undefined here we'll just evaluate to nothing so we just get u r and then this turns into nothing blank years old and that's exactly what we see here you are blank years old i can just add a default value like i would for any other object that i'm destructuring so i'll say the default value for age maybe is 18 and where's my browser here we are you are 18 years old otherwise if an age is passed in we'll use that age now it's really important to understand that the props that we're passing right now are all strings but we may want to pass a number or a boolean or an array even an object we may want to pass things that aren't just strings and the syntax is a tiny bit different if i want to pass an actual number why don't we make a prop called excitement excitement for your greeter it will dictate how many exclamation points there are so if i do quotes like 4 that is a string to do a number or any other data type a non-string i use curly braces and then in here i could put a variable or i can just write a number like four let's do excitement down here excitement is going to be equal to how about 2 okay so now i'm going to use that prop excitement in my component to control how many exclamation points we put after the name so i'm going to destructure it here excitement we could give it a default value of one maybe for one exclamation point and then the method i'm going to use to create a bunch of exclamation points depending on this value is to use the string method repeat which i don't think is actually supported in all browsers but just to make this short i'm going to add it in right here curly braces after the name and then the string exclamation point dot repeat excitement times i should have maybe called it excitement level or something um and let's see what we get hi there karen four exclamation points hi there tammy two and then if i leave off excitement we should just get one exclamation point and there we go okay so i won't show you passing booleans and arrays and objects and other data types but we can you can pass whatever you want inside of those curly braces if you use quotes it will be treated as a string even if it looks like a number so props allow us to pass in properties uh configuration information for components but it's very very important that you know props should never be changed inside of a given component so i should not be changing the value of excitement or age in this component props are there for configuration you pass them in from another component typically and then we can use them in this component but we should not be altering them from this component now technically with the way that we've set this up where i'm destructuring each one of these variables name excitement and age is going to be a new variable based off of the props object so i actually can change one of them like i could set age to just always be 45. i should not do that it's against the principles of react prop should be treated as immutable unchangeable within a given component but if i did something slightly different if instead of destructuring if i just went with the props object here and i'll just comment all of this out for now and if i wanted to update props.age and set it to be 45 or i wanted to plus equals one if i go to my browser now i'm getting an actual error cannot assign to read only property age so my little destructuring shortcut is not my shortcut it's really common to see but destructuring those props makes new variables but if we actually reference the original props object it tells us you're not supposed to change that in fact you can't change it it's a read-only property so even if we can change a prop because we are making a copy of it like i'm doing here you should not change a prop within a given component now that doesn't mean we can't have react components that change or update or have new information that's just not something we've talked about yet that's where state comes in but for now we're just talking about props next i'd like to quickly talk about events in react now we're not going to go into much detail on this topic but obviously events are very important when we're creating an application we need to be able to respond to clicks or hovers or drags mouse overs mouse leaves keyboard presses or key presses key up key down lots and lots of events and typically without react we would probably use add event listener the dom method to add i don't know a click listener to some elements blah blah and we have our callback well we do things slightly differently with react remember these are not actual dom elements these are jsx elements which which turn into react elements which are not quite the exact same thing but basically we need to go about this using the react way and thankfully react gives us some event listeners that we can add on to any of these jsx elements and the one i'm going to show you is on click so on any elements let's do our h1 here or maybe we'll just add a button here let's do a button element click me and then i'll add an on click attribute just like this with a capital c and then i'm going to add curly braces here so this is not the standard dom on click that you could add to any non-react element uh that would be with a lowercase c this is an uppercase c this is the react on click and then in here i can call some function what you'll sometimes see is an arrow function like that so on click i want you to alert hello and now if we click that button we get alert of hello so that's one option we also will commonly create a separate function and you can actually just define a function inside of greeter i could do something like const greets equals function and then in here i will i don't know maybe we'll alert let's use a string template literal hello there and then we'll put the name so dollar sign curly braces name and then here i won't use an arrow function i'll just add a reference to my function which is called greet so whenever somebody clicks on a button inside of a greeter i would like for the greet function to be executed so we don't put parentheses here because we're not executing the function right now we're telling on click what we want to be executed when the time is right when a click actually occurs on this one button so now i click and we get hello there karen and hello there tammy okay so that's just a really brief introduction to on click there are other react events so i could change this to be on mouse over for example although that's going to be kind of annoying more than kind of annoying it's extremely annoying as i mouse over here i get that alert we also have a whole bunch of other ones if i just type on in vs code you can see lots and lots of different events that we can work with and they all follow this pattern you add them to some jsx element and you add them as attributes and you set it equal to some function and that function can be declared on its own or it can be declared inline using an arrow function most commonly all right so that's a very brief intro to react events now it's time to introduce the second essential react concept the first one was props the second one is called state so props is data that is passed to a component it's for configuration purposes state is data that is managed inside of a component and it can change within that component so state is how we can start to make things that actually change and are interactive so instead of just alerting something when you click on this button or you mouse over let's go back to a click maybe i want to have a simple counter that you click and it increments a number and it actually shows up on the page it's not just an alerts but we're actually rendering let's say count or num or total and as i click i want that to update well that would be a piece of information that needs to change in this one component and props are not supposed to change so state is the key to adding any of that in i'll show you a few examples back to home depot we've got this shopping cart again where i can change the quantity of items and as i change the quantity here you'll see that the item total changes we get the cost of the item multiplied by the quantity so i'll go to three there's no page refresh involved all this happens immediately and it's done using react so when i change this number there is code in some react component that is updating a piece of state let's say it's just called quantity that's probably what it is called and what's essential to understand about state is that when a piece of state changes in a component the component is re-rendered so this item total here is just going to be the price times the quantity and as i change that quantity that triggers a re-render because i'm changing a piece of state here's another simple example we've got this component from a code pen a five-star rating component where i can change the number of stars i can click and it actually updates that component what does that mean well there's some piece of state let's call it num stars or rating or something and as i click there is code to change that piece of state so we will spend a little bit of time talking about states and this is really the first piece that we're going to see of react that involves hooks and is substantially different from how we would implement it with a class based component so i'm going to make a new component just to make this simpler i'm going to make a pretty standard basic component i'll call it counter this is a really common demo in react kind of like making a to-do list or something so i'm going to start by importing react from react and then i'll define my component i'm going to call it counter so function counter we won't have any props right now and then export default counter so what i want here is to have two buttons and a number that's displayed so why don't i start there i'll return how about a div and in that div we'll have maybe an h2 that has some number for now i'm just going to hard code it as 12 and then we'll add a button and this button will say something like how about just plus one so i want to click this button and have this number update let's just render our component and make sure it works i always like to do that first to find the very very basics without any logic go to my app import counter from dot slash counter okay and then i'll render a counter probably just at the top so i don't have to scroll down and there we go i've got my basic components kind of ugly and it doesn't do anything also i don't know why i mentioned not wanting to scroll down there's plenty of space i wouldn't have had to scroll okay so what i want to do is make this a variable a piece of data that can change not hardcoded as 12. to do that i need to use state so to tell react that we want this component to use state there is a particular function that we need to import called use state it's part of react so i could just call it like this right here react dot use states but what's most common is to actually use a named import which looks like this and grab use state from react and it's going to complain that i'm not using it right now but i will in just a moment so before i return anything i'm going to call use state and use state is really really nifty it's very different from how we would use states in a it's very confusing sentence but it's different from how we would uh incorporate states into a class based component it's radically different so it's just a function use state and then we'll pass in a initial value for this one piece of state that we're reserving and for us i think we'll just start with the number zero so that will be our initial value we'll display that here first and then as you click we'll add one to it now this returns an array and this array includes two pieces two things the first thing is the piece of state itself and the second thing is a function to change that piece of state so most often we destructure this so that's what i'm going to do here the first thing is a reference to the piece of state which i'm just going to call num or count total you can name this anything you want let's go with count and then the next thing will be a function that will actually update that value and it's common to use this pattern count set count or total and set total years and set years color set color this is a function this the first thing that's returned it's always based off of the order the very first thing is the value so function value and then i'm going to render count right here just like i would any variable and it's not going to be very impressive at first because we set count to start as zero and it's never going to change with what we have right now it will stay zero but let's verify that we do have zero showing up okay great news we've got zero so there's a piece of state we're calling it count and it is never changing but it starts at zero and we're rendering it here but now for the important part i can call set count how about when we click this button we'll call set count and update the value of count to be something else so i'm going to add an on click right here and i'll start with just an arrow function and we'll call set count and i'm going to pass in some new number how about 99 just to begin with so we're calling set count and whatever value i pass in here will be the new value for count so it started at zero if we click once it will go to 99. let's verify that that happens so i'm going to click and magically we now have 99 showing up here so what happens again is that we're calling set count when we click that sets the value of count to 99 and remember what i mentioned a couple minutes ago when a piece of state changes in a component the component itself re-renders and that means that the new value of count will be displayed right here it's no longer zero so that is how we can make components that change very simple example but instead of hard coding 99 let's increment count we can take the current value of it and just add one let's see if it works click click click click click this is a super essential concept in react it takes a little bit of time to start to wrap your head around the syntax is very simple thanks to hooks we can have multiple pieces of state so why don't we do another example we'll make another piece of state instead of it being a number let's make it a simple boolean and this will be our mood happy or sad or is happy true or false and we'll have a little happy face that flips to a sad face depending on that piece of state so i'm going to call use state again use state and i'm going to initialize it not to zero but how about to true and then i need to come up with two names here what is the piece of state the actual value why don't i call it is happy that will begin as true and then i'll write set is happy now once again it does not have to be this pattern these are completely up to you but it's just really common to see this pattern okay so is happy and set is happy and then maybe down below i'll add in where should i do this this is kind of a silly useless component but i basically want a happy face or a sad face depending on if i can type a sad face depending on if is happy is true or false so maybe i'll do it in a h an h3 maybe sure so instead of just hard coding a happy face i'm going to use a ternary based off of is happy so curly braces question mark is happy is that true or false if it's true i want you to render this string right there a happy face if it's false i want you to render that string a sad face all right we get a happy face but i want to be able to click on it to change if it's happy or sad so i can add an on click to an h3 it's kind of not it's not a good practice because nobody will know to click on this h3 and it's not accessible really if you're using a screen reader how would you know to click on this but just to make this demo short and simple i'll do this here and instead of doing it inline i'll make a separate function called change mood so const change happy or change mood or maybe toggle toggle is happy will be a function a very simple one probably just doing a one-liner where i'm going to call set is happy and i'm not going to pass in true or false because then i'm setting it to true or setting it to false every time i'm going to pass in the opposite of what is happy currently is whatever value i pass in here will be used to update the value of is happy okay so let's see if this works i'm going to pass that reference to toggle is happy when you click on this h3 call this function it itself calls set is happy using the opposite of the current value for is happy so it starts as true and that's what we see now i click on it and it goes to sad back to true false true and false and we're changing what's being rendered so a very simple example but this demonstrates that we can have two pieces of state or as many as we want we can have numbers booleans anything really and it's just another example of how we use the second piece this function that's returned to update a piece of states which triggers a re-render meaning that we see the new value being rendered we see two instead of one we see three instead of two or we see a sad face instead of a happy face or vice versa before we go any further you may want to install the react developer tools uh this is the chrome version there's also a version for firefox there may be a version for other browsers but those are the two that i've used they're really really great developer tools so if you want to continue with react i definitely recommend you install them so i have them installed and i can open them up if i open up my developer tools in general on a page that has react on a react web page i will have two different pieces that are new from the react developer tools and we're going to focus on components so components here is giving me a hierarchy of the components in my application the actual react component so we've got our top level app the one thing we're rendering into that root div and then we've got just a div and then a counter component a navbar component a greeter component another greeter and some random h1 that just says hello okay so if we look at one of the greeter components we can see the props over here so these are just showing the values that this component has in the props or props that have been passed to it and then if i look at counter counter has two pieces of state now the names that we gave those pieces of state what was it count and is happy those don't show up here because those aren't real names that reacts knows about those are just variable names that we created so it's just a container for some piece of state you can name it whatever you want anyway we have these two pieces of state one is set to three currently and if i increment here it now goes up to four there's sometimes a little delay with the dev tools but you can see eventually changes to five and then we've got this other one here i click it now toggles to true so what's really important and what i want to highlight right now is what actually happens when the state changes so there's a setting in here that i can turn on highlight updates when components render and i'm going to change the state here and i'm going to zoom in on the left side and watch this component up top the counter component as i change some value in the state i'm just going to change it through the dev tools i'll go to 10 and hit enter here can you see that border that just applied for a moment that indicates that a component re-rendered because of this setting that i toggled so a re-render is basically what it sounds like this entire function is going to be executed again and this is kind of confusing it seems like that wouldn't work the whole function is executed but what changes is that we now get a different value for count so if i click plus one let's refresh the page we start back at zero the very first time this function runs react executes this function count starts at zero is happy starts at true but let's just go with count so then it returns this markup right here this jsx and there's an h2 that has the count so we see zero but then when i click this button i'm changing a piece of state i'm calling set count and because it's a piece of state that changes that triggers a re-render anytime a piece of state changes your component will be rendered so the state changes and it goes up to one but the really interesting part is that our component the actual rendered content isn't going to change unless the function is executed again so when the state changes whenever we have a piece of state that changes the component re-renders meaning the entire function is executed again but the magical really cool part is that count is not going to be set back to zero even though it's just a function running again thanks to the way react hooks work and things like closures there is persistence so count will now be set to the new version of count when this function runs again and then it returns an h2 that has one if i click again it updates the state so that count is now set to two but think of it as a value that is stored somewhere else react is in charge of that value and it executes this entire function again because we change the state that triggers a re-render and now this line acts to fetch the latest value for count so every time this line runs and it runs a lot it runs every single time this component re-renders which happens every time i click this button every time that happens this line is going to fetch the latest value for count except the very first time it ever runs this initial value will be used to set count every subsequent time count will be filled with the current value the latest value from the state so re-renders are very important to understand if you change the state the component re-renders and every time i click we get a re-render which is not an inherently bad thing a lot of people get caught up on this idea of well the entire component's re-rendering again that seems inefficient don't worry about that for now state is a relatively complex topic that we're just scratching the surface of in my react course that i have there's a couple places i teach react in depth we spend a couple of hours talking about state for now we're just working with a boolean and a number those are both primitive types but if we store things that are reference types something like an array or an object there are considerations when it comes to updating the state there are patterns that we should follow we're not supposed to mutate the actual object or the array but i'm not going to go into that right now all you need to take away from this is that use state is a really cool function that comes with react you execute it pass in an initial value and it returns to you an array that array has two things the first thing is the piece of state itself the second thing is a function that you can call to change that piece of state and we can combine props and state what if i wanted to make a counter where i could count by two or three or five i could have a different step instead of just one well that would make sense as a prop for each component we're probably not going to change the interval for one specific counter within that counter i mean but we might have three or four counters and each one could have its own step so that makes sense as a prop it's not something that needs to change and just in general you want to try and minimize the information that you store in state that's a principle in react that's important minimize your state as much as possible so i'm going to make two counters here and i'm going to pass a step into one of them as a prop and this will be a number so i'm going to use curly braces not quotes for a string and let's have the step be 5 and then in my counter component i'm going to destructure step and i'll give it a default value i'll set it equal to 1 if you don't pass in a step and then i'm going to replace this right here where we're actually calling set count and adding one to count we're going to add step to count and let's see what happens to the first one we're adding five the button says we're adding one so we could update that plus curly braces step whatever that step is we see plus five and here we see plus one we didn't pass in a step as a prop we're using the default value so next up let's talk a little bit about styling react components so this is actually a big topic there are libraries people use in particular there's one called styled components that is quite popular i'm not going to go into that that's like an hour or more of my react course it's just a lot to talk about but i am going to show you two different ways of styling components so i'm thinking that i'm actually going to move this is happy set is happy the toggling functionality for this h3 into its own component just to simplify things so i'm going to make a mood toggler component dot js and i'm just going to copy this whole thing over just to make this quicker i'll import react and use state from react i'll rename this to be function mood toggler and we don't need a step or any props there we don't need count we need is happy set is happy we don't really need this div even i could just add that h3 in there and then i'll make sure i export defaults mood toggler and then let's render one of those in our app.js so import mood toggler from dot slash mood toggler and then we'll render one how about right there mood toggler okay and then in my counter i'll get rid of all that is happy stuff and hopefully everything works we still got that counter step of five step of one and my mood toggler okay so let's talk about styling now now that we've just simplified things and split them up there are two main ways of styling in react the first is to just write regular old css styles in a style sheet and add a class or an id or something to an element so if i wanted my counter what would i want to do there maybe i want the counter to have maybe text align center and maybe i want the button to be a bit larger or something i can write those styles in a css style sheet and the conventional pattern with create react app is to make a stylesheet that has the same name as your component javascript file so counter.js counter.css now you don't have to do that but it is conventional and i'm going to go ahead and do that here so counter dot css and i'll begin by setting that h2 to have a text align of center why don't we start there text align center okay now it's not going to work because i haven't included that css i need to import that css somewhere and typically we'll import it in the component itself but you should know that this css is in no way scoped to this component i am simply telling webpack that i want to include this one file so i don't have to actually import the css file here i could import it in my app the way we import a css file is just like this right here we're not actually using it in our javascript we're not importing some piece of it we're simply telling webpack make sure you include this style sheet when you're building me my bundle with all the javascript and css and other assets so i'm going to do that in here which again you don't have to but we need to do it somewhere in one of these components that's actually being included so dot slash and then counter dot css and zoom out there is our counter well the h2s are centered but if i had styled something else if i had said you know buttons i want you to have a font size of two rems all buttons are going to get larger it doesn't matter that i'm only importing it these styles into the counter javascript file it's irrelevant so what we usually do is add a class name to our component like the top level div or whatever the top level one element is that we're returning and we give that a class name that matches the component so i would give this a class name of counter and then i could write styles that are going to select based off of counter so the h2 in counter the button in a counter component and the way that we add a class in react is a little bit different if i do class equals counter that seems like how we would do it in html and it probably will work and it does work my styles are only applying to the counter it looks awful but it is working if i open up the dev tools however i will get a warning here invalid dom property class did you mean class name so in react we don't use the normal attribute of class we use class name and the reason for this uh is that i think it actually doesn't matter these days and the fears may have been unfounded i'm not positive but originally the react team or people on the react team were concerned about using the name the term class because that is a reserved word in javascript right we define a class class dog we use that keyword so they decided to go with class name but as you saw it did technically work with class class name is just what you'll see all over the place and it's what you should use so this is one option for styling things we could make this look slightly nicer but if we do counter component maybe give it a border of i don't know two pixels solid black and a width of what should we do uh 200 pixels and then let's do margin auto so it's centered and then maybe a bit of vertical margin how about just one ram okay fine enough and then instead of centering the h2 i think i'm just going to center that entire container div so that my button is centered all right good enough there's our counter nothing spectacular but we have some styles that are applying to that one component now the other option that we have that i'm going to show you is to actually inline styles to add styles directly inline as part of our component definition and this can be useful if we have dynamic styles so for this mood toggler i may want a different color for this h3 for this happy face versus a sad face maybe i want a green happy face and a red sad face and to inline styles we have a style attribute that we can add on to an h3 or i don't know why i said in h3 we can add it in to any uh jsx element it looks like this style equals and then we add our curly braces and inside of those curly braces we actually pass in a javascript object so this is not regular uh you know html the style attribute that we've seen before you likely have seen before and have been told not to use this is different uh it is a react or a jsx version and it's expecting an object so we actually if we're going to do it in line we need two sets of curly braces the first one in yellow is indicating that i'm writing javascript basically it's escaping regular old jsx syntax and then the second inner pair is a javascript object and now i can set things like color and i'll set color to be red just to start it will always be red and it's a little hard to see but there it is it is red now if i wanted to do something like background color in css it would look like this but that is actually invalid in javascript we can't use a dash or hyphen or whichever it is in an identifier so we have to camel case everything so this is different from css same properties like the same spelling and everything except for the fact that they are camel cased not kebab cased so if i do background color camelcased there we are it's hideous but it works so if i wanted to add a dynamic color red or green not just always red i'll base it off of is happy and i would do probably just a ternary operator again is happy question mark i'll set background color to green or red and there we go we get the green first and then we get the red i think i would go with just regular color not background color and another option would be to move this into a variable just const styles like that just to clean up our markup and then i can pass that variable in right here that is my object all right so it's going to look awful as we've seen so we could also add in some regular css styles using a class name or something so i could give this h3 a class name of mood toggler just like that sometimes you'll see this done if you have a lot of attributes going on you can indent them you can get pretty fancy with indentation especially when you've got these ternary operators and if your statements are long this is pretty short so it's not a big deal you'll see a lot of weird indentation stuff all right so i have this class name of mood toggler now i can make a nice little mood toggler.css file and what do i want to do here i think i'm going to go with a larger font size so select that class mood toggler a larger font size what should we do two rams i'm not sure we'll play around with it and i'm going to do a text align center and what else do i want to do maybe add a bit more padding padding one rem and then i'm going to import this css style sheet so import dot slash mood toddler dot css let's see what we're working with here okay so it's a little bit larger let's blow it up significantly more let's go for maybe five rounds font size okay and now we have our mood toggler still not a great component because i mean it's silly and trivial but also i wouldn't make an h3 clickable but just for demo purposes this is fine next up we'll tackle a slightly more complicated component which is actually multiple components working together by the way if i sound slightly sick i apologize i'm recording this on another day and i'm having a horrible allergy attack but i need to get this out so bear with me anyway this is a shopping cart that consists of multiple components and it's a opportunity for us to discuss something that's really really important in react called the downward data flow or state as props there's different terms for this basically i'll just give you a quick run through we've got our main shopping cart we've got a total down here that totals all of the subtotals for each item i can change the quantities it's kind of janky right now i haven't added much css you know so this button's hopping around and these things are shifting but you could fix that relatively easily with some nice css but you can see that the total updates over here based off of the quantity and then the total at the very bottom also updates the sum of these three elements also if i try and go down to one i can no longer click any further we get this slightly grayed out or more grayed out button so i can't delete an item at least not here but i could easily add a delete button i just didn't want us to go into the negatives to have negative 20 sour creams so it's still very simple right it's it's nothing crazy and it's kind of the same idea as what we have here just a counter except there are a couple differences first of all there's a price uh we're going up and down and we're figuring out the total or the subtotal but the bigger difference is that we actually have multiple quote unquote counters which aren't quite counters but multiple items where all of their subtotals are totaled up into one grand total and with the counters that we've seen these are completely disconnected they have nothing to do with one another yes they're both instances of the counter component but they're not connected i don't have one place where both of them are storing their data each of them has a piece of state and it's siloed it's often an island in the middle of nowhere they're not connected so to make this work what we're going to do is have our main shopping cart component everything that you can see in this white box here and then inside of that we'll have a shopping cart item component we'll have three of them in this example and we'll need to figure out where we put state where do we put the quantity for each item it seems like the obvious place would be to put it in each card item but that is not going to work for us if we want to have a grand total as we've seen before we can pass data down using props from one component to another as we've already done if we go to our app right we've done things like this passing name to greeter or age or excitement passing step to counter but this only works going from a parent component to a child's component so what this means is that if we're going to have information that we need to have access to both in a child component and in the greater parent component in this case we need to know the quantity here but i also need to know the quantity up here so i can multiply and figure out the grand total for each one of these items sum it all together so we need the quantity in the child component and in the parent component and to do that we're going to have to store the state the actual quantity information will be in the state of the parent and then we can pass it down to the child so this is a bit confusing but it's one of the most important central ideas in react it's something you do all the time states as props we have state in one parent component that manages it it oversees the state and then it can pass pieces of that state down as props to child components so we'll have an array of items in our shopping cart component in the state and then we'll loop over that and render a cart item component for each one of those elements so let's get going let's not worry about the styling we'll do that at the very very end it really doesn't matter let's just get going on the basic functionality okay so we're going to begin by making our cart component we could call it shopping cart or just cart and i'll name the file cart.js i'll import react make this a bit larger here from and then we want to import that from react all right so then i'll define my cart component and we'll export defaults cart at the end and then i'll just return something really simple here why don't we return uh i don't know a div with an h1 in it that says i am cart i always just like to make sure things are hooked up correctly in my app.js i will now import the cart component from dot slash cart and then i'll render one just at the top here and there it is now by the way i changed the background color of the entire body which generally you do in your index.css so the index css file is for styles that don't apply to particular components they might be generally their application wide things for example to change the font family of the body i'm using a google font here i set a background color really nothing to do with react it's just a place where you can do that but of course i could do this i could style the body from any of my css files i could do it in counter.css and say actually the body here has a background of magenta and it all just comes down to the order that those css files are loaded in but generally you want to do those sort of changes in your index css which is already made for you i didn't make that file anyway we have our cart component and our cart component is going to have an array that we store in state and the array is going to look like probably something like this where we have a bunch of items different items that could be in your cart and each one might have a name a product name like taco shells i guess and then a price like uh 3 25 and then a quantity let's go with two we'll have something like that and then we'll have a bunch of those so um i guess i think i have one on my clipboard there we go so i have this set of items here now typically if this is a real application we're not going to hard code any of this this would be coming from an api somewhere from a database maybe or from local storage we're not going to hard code this into the cart component so what i'm going to do since we're not working with an api and we're not working with local storage right now is that i'm going to pass that in as a prop i'm going to call it items or initial items or something maybe just items and that's going to be that array so i'm just going to declare that array up here for now just outside of my app component and then i'll pass that in items equals items okay so we have a prop which will be an array uh i also gave each item an id and you'll see why in just a bit and then i just have three different items i i just made up random prices random quantities apparently we're having a taco night at home okay so in my cart component i now can expect a prop called items so there we go i can uh destructure that from the props honestly i might want to call that initial items okay so i have this initial items prop and what i'd like to do is loop over the initial items these three items in this case and make some markup for each item i want to display the price i want to display the quantity the uh what else the name that sort of thing so below i am cart i'm going to add in a loop and we haven't seen this yet but we can loop within jsx and the most common way by far the most common way of doing this is to use the array method map so in jsx if you have an array of elements that you're returning somewhere an array of jsx elements for example an array of divs or an array of components they can be rendered one at a time to the dom so map makes that easy it returns an array already just a regular old javascript array but what we're going to do is map our initial items so initial items.map and i could start by mapping each one to maybe just an li just to keep it simple so for each item i'm going to return an li and this li will have what should we do name what did we call that yeah just name so name colon and then we'll display item.name let's just start with that and i think i'm going to wrap these in a ul now we're going to move this into its own component in just a bit but let's make sure that this works and there we go name taco seasoning name pinto beans name sour cream cool so we also have things like price right item.price and that's showing up as well so this pattern is really common mapping over some array and each time through map we return some jsx element or some component a standalone component which is what we're gonna do right now so let's make a component instead of an li here let's render a cart item or something like that and it doesn't exist at the moment and we'll pass through our props from this initial items array we'll pass through things like what do we have price name quantity that sort of thing so i'm now going to make that component i'll call it cart item dot js and i'm going to import react from react and then i'll define my function cart item and then i'll export default card item okay then in here i'm gonna return probably a div we'll play around with the markup but i'm gonna begin by just following the pattern i laid out earlier where we give the top level element of each component a class name of that component so card item will be the class name for this div and then in here i'd like to display the name that each cart item has but that's going to be a prop that is passed in so right now we're not accepting any props and nothing is being passed down so over here if i do want to map over initial items and return a cart item i need to do a couple of things first of all i need to make sure i import card item so import card to item from dot slash card item but that's not enough that's just gonna render me i mean it will work with what we have right now but it's just gonna render an empty div there we need to pass through each piece of the item so what do we want from each item well if we go back to look at what our items look like we have an id a name a price and a quantity so there are a couple of options for how we do this i could do one at a time i could say id equals curly braces item.id item is just the placeholder it's not a placeholder but it's the parameter here for map so i can name that anything but it represents each individual element in that array so i'm passing through the id and then i could pass through a prop called name and set it equal to item.name and keep going or i can destructure all of those props or destructure that entire object into cart item as props just like this so this will now give me a prop for every single uh property in this object so id name price and quantity and i can destructure that if i want or i could just have props here but i'll do id name price and quantity just like that and i should now be able to render name if we want to start there let's see if we're getting each product name and there we go taco seasoning pinto bean sour cream so all we've done really is added this layer of abstraction where we now have a cart component and a cart items component and it makes no sense to render one of these components a card item which gives us a div we don't want to render that inside of a ul it's actually invalid html to have a div as the direct descendant of a ul so i'm going to redo this markup ever so slightly we'll put a div here and give this a class name of what should we do how about cart dash items and that's where we'll put all of our cart items inside and then i'm going to give this top level div the class name of just cart following that same pattern we haven't done any css yet but this is just easy we can hook back into it when needed we know the top level is cart or cart item all right so aside from just the name we're going to want to display the price we'll display the quantity and we'll display a total price as well or a subtotal for each item got that first div let's do another div where we display the price all right eventually these will be on the same line but there we go we've got the price let's put a dollar sign in front of it okay and now let's do another div here and we're going to display the quantity so qty and we'll also add some buttons in where we can change the quantity but for now we'll just start with that we have our quantity our price and our name and then let's display the total and we can just do the math right here so to display the total it's going to be the quantity times the price so qty times price total 4.5 right 225 times 2 199 times three okay that looks good uh let's put a dollar sign there as well so we're just displaying the information it's not very pretty but we're displaying it here that's all the important stuff and we're doing it in a separate standalone component that we are rendering from within cart we're looping over the prop initial items and uh mapping over that to create a bunch of card items that are each rendered now if i open up my dev tools here in my console i'm getting this warning it says each child in a list should have a unique key prop so any time we're mapping over or looping over something we're going to get that error message or technically a warning from react if we don't supply a key prop so a key is just a unique identifier that reacts can use to keep track of these individual cart items and know which one is which it's an it's internally used and it's really important that we add it even though right now it's not going to make a difference whatsoever it's just something you need to get in the habit of doing so fortunately each item already has an id so we can just use that id as our key so it's as simple as key equals item dot id so we'll do that every single card item has a different key prop and if i open up my console again that goes away okay so what i'd like to do now is display a grand total from our cart not the subtotal for each item but a total down at the bottom so we'll do that inside of the cart component probably a h i don't know h3 or something uh we'll deal with it later let's just do grand total and then how do we calculate the grand total we have all the individual items here nothing's changing at this point we don't have any state involved but we will how do we calculate that total all we need to do is loop over every single item multiply the price times the quantity and add that into some variable the easiest way or at least my favorite approach is to use reduce so i can make a variable up here i'm not going to do it in line i could it's just kind of a lot so i'm going to make my total variable or grand total or something like that and set it equal to initial items dot reduce and then if you're not familiar with reduce not going to go into a whole lot of detail here but basically we need our accumulator variable or parameter and then our second parameter is the individual item and then for each one i guess i can use an implicit return here we're going to return total plus item dot quantity times item dot what is it price and then we need to pass in the initial value we want it to start at zero so it's going to loop over every item in initial items and for each item we multiply the quantity times the price we add that to the total and our total begins at zero and then here i should be able to render grand total okay let's see what we get oh lovely math issues with floats so i'm probably going to round that to what should i do i guess i'll use two fixed probably just chain that on right here two fixed two and that should fix that issue for us let's see there we go thirteen ninety seven and i'll probably add a space so nothing is changing whatsoever at this point it is completely static what i'd like to do is have a button on either side to increment or decrement the quantity for each one of these items and this is where things start to get uh not necessarily interesting but reacti our individual cart items is where we want that button to be i want i can add them right now next to the quantity in a div i can have a button here button and we'll just have a minus sign and then i'll do another button on the other side with a plus sign so we can make those buttons but i want them to increment the quantity for this one item and if that was all i needed to do that's easy enough but we have the cart itself which has a grand total and i need the cart to know when i'm changing that quantity and if i change some piece of state in a cart item nothing else knows about that just the one card item that i'm changing so i need to make my state all the way up here it's only one level up fortunately but in react often we will have state multiple levels up that we then pass down at the moment we're passing down props to each cart item the quantity the the name the price the id we're going to continue doing that but it's going to be coming from a piece of state that we make in our cart so i'm going to make a piece of state and to do that i need to import use state and then i'll just call it items and then set items equals use states and i don't want it to start as an empty array i want it to start as initial items whatever is passed in initially i want the same first render that we have right now but then i want it to potentially change as we increment or decrement quantities so i have my initial items as the initial value and now instead of looping over initial items i'm instead going to loop over items which is coming from the state and same thing here this will now be items.reduce otherwise i think that's the only change we need everything still works and looks exactly the same so that now brings us to the next issue which is how do i change the state from a child's component how do i change the parent's state that's what i need to do in this component quantity is just a prop i'm not going to change quantity in this component i don't do something like quantity plus equals one and i could try that for example i could make a click handler const increment quantity or just i don't know how about just add one equals a function and all it's going to do is set quantity plus equals one like that and then i'll call that when you click on the plus sign on click equals add one let's see what happens we'll click nothing's happening why not well we're changing a prop which we're not really supposed to do from within a component but more importantly react only shows us an update it only re-renders a component if the state changes or if a component gets new props from a parent right now neither of those are happening so even if the variable quantity is being incremented in javascript react is not going to re-render this component to show us the new quantity so this approach does not work what we need to do is find a way of saying hello parent component i want to add one or subtract one or do something to your state my parent and then when that state changes in the parent that causes a re-render of this component the cart component which means we loop over items and then we re-render cart items each individual cart item they will get new props so we'll see a new updated quantity and a new updated price and not the price but the updated total will be displayed as well so how do we do that well we passed down a function from our cart component to the child components so i'm going to define a function up here i could name it anything what should we go with here how about just update quantity update qty equals a function and remember that our state items is an array what we need to do is write a function that can update the quantity for one item in that array and to do that we're going to need to know the id of that item that we're trying to update because there are three things right now there could be a dozen or more how do we know which element or which item we're supposed to add one or subtract one from the quantity well this brings us to a very important point around state in react if we're working with arrays and objects we never want to mutate the original array or the piece of state that we're trying to change so we have this array that has three items in it and the easiest thing would be just to keep everything the same and then add one to this quantity or subtract one what we do instead is create a copy and use that to set the state and the reason for this is that react is going to compare previous state and new state in order to figure out if it needs to re-render and it can get tripped up or not realized something has changed if we're only modifying or mutating an array or an object rather than creating a new version a new copy so it's a really important topic in react updating state properly and not mutating any of your data structures unfortunately it does mean that often our code gets a little bit longer so if we're going to write this update quantity function it accepts an id it should also accept a quantity how are we going to update the quantity is it going up by 1 or 2 or 20 so what we're going to do is loop over or map over all of the items in our state i'm going to make a new variable here called new items new items equals items.map and for each item here i'm going to check if that item.id is equal to the id that has been passed in this id meaning if we found the thing we're supposed to change i'm going to return a new object that looks exactly the same as the original item but the quantity is now some new quantity that has been passed in so why don't i call this new quantity just to make it clearer otherwise we're just going to return the item as is but we're mapping so what this will do for us if i just copy this over for a moment let's say we're updating uh the thing with id of 2 and we're setting the quantity to 4. so we map over all items which makes a new array we're making a copy of everything in here if item.id equals the id we're looking for well it doesn't for the first thing so we just return the item but when we get to id of two that is the thing we're looking for we'll make a new object that includes all of the data so id name price quantity except we also change quantity here to be the new quantity so making these changes to states the correct way involves lots of destructuring what else object dot assign array methods like map and filter it takes a little bit of getting used to if you're not familiar with it this is something you know we spent a lot of time talking about in my react courses because for a lot of a lot of students it's just not the way you're used to working with arrays or objects anyway we're only part of the way there it's a hard part but we've just made a new variable that's it we haven't actually called set items that's the last thing we need to do here set items with those new items so this function whenever it's called it expects an id and it expects a quantity to set some item to a new quantity and it's going to make a new array a new items array and then call set items at the end now what we need to do is get this update quantity function down to our child component so that we can call it from within here when you click one of these buttons and to do that it's as simple as passing any other prop so i'm going to pass that here i'll call it and probably just update quantity and then i'll pass it through update quantity that's the name of my function here now in my cart item i can destructure that if i want to so update qty is a function i can call so now let's start with the increment button when you click we can't just call update quantity it's expecting two arguments the id and it's expecting the number that we're incrementing by or the new quantity so i could do an inline arrow function here what i'll probably do that i prefer is to write a function up here called how about just add one and add one is going to call the parent function that was passed down this changes the state in the parent there is no state in card item and we'll pass in the id of this particular component and then we're going to take the quantity and just add one for that second argument so here we'll call add one which is a function defined in this component and that function happens to call a function passed down from the parent that adds one to the quantity in the states of the parent which is going to call set items which changes the state which means everything is re-rendered in this component which means our component cart item gets a new series of props and those changes are reflected in the dom hopefully fingers crossed let's see what happens when i click hey check it out so our quantity is changing here total is changing and the grand total which is in the parent component the cart component is also updating we need to make decrement work so it's as simple as writing another version of this function const i guess subtract one and we'll call updates quantity you know we could do this on one line too if we just use we don't really need to return anything so i'll just do it like that update quantity with the same id we'll take the current quantity and subtract one and then here when you click that minus sign button we'll call subtract one okay subtract add subtract and i'd like to add a safeguard so that we can't go negative as you can see there uh my total is now negative 11 times 20 or 2.25 not what i'm looking for um so i'm gonna need to add some logic either that says if the quantity is less than one don't update it or if it's less than zero what i'm probably going to do is actually a really simple change i can disable a button in react by adding a disabled attribute and what's cool about it is that i can programmatically set it based off of some some logic so i could just say disabled equals true if i really wanted to and now that minus button is permanently disabled but what i want to do is disable it if our quantity is 1 or technically if it's less than one i guess i don't want you to let to be able to click it anymore so i'll just say disabled equals quantity less than or equal to one so you can see that i can add and subtract but then as soon as i get to one i can't subtract any further we would probably have a delete button which we're not going to uh implement right now but that would make the most sense this is not the best interface anyway it might be better to have a drop down or a text input where you could type a quantity but it's basic enough and it illustrates the really important principles at play here of having some state and a parent you pass it down as props to the child components and then you also pass a function down that you can call from within a child to update the parent state so let's add some basic styling this is not going to be very react centric at all it's just basic css there's actually nothing specific to react here but i'm going to start by styling my cart so i'll make a cart.css just conventional stylesheet here and i have that class i defined called cart and i'm going to use that here so dot cart i'll give it a width i think i did 750 pixels margin and then a background color of white and what else did i do a border radius six or seven pixels i think and before i go any further let's import that style sheet so import dot slash cart dot css and let's see what we end up with all right so we've got our style sheet connected let's fill out a little bit more i've got my border radius i'm going to give it a box shadow 1 pixel 2 pixel 3 pixels and then 0 pixels and i'm going to do a black that is very dilute rgba zero point i don't know let's see what that looks like 0.5 that's a bit dark how about two okay good enough and then i'm going to set it to be a flex box so display flex i have a video on flexbox if you need some assistance on that and i'm going to give it a flex direction of column okay and i'll give it a little bit of padding okay next up i'm gonna add some styles to the what should i do maybe the title of the cart so instead of just i am cart i guess we'll just display shopping cart maybe and we could give that a class name of cart title and let's give this h2 a class name of what should we do class name maybe cart dash total and i'm thinking instead of an h1 for this maybe an h1 is fine okay now let's go to our cart css we have cart title and cart total cart title is going to have a border bottom and i'll set it to be one pixel solid gray i might change that color and i'll give it a color of gray as well and a font size it's not super large maybe 20 pixels and a font weight that is on the lighter side now let's work on the individual cart items so we'll make a cart items or cart item css file cart item dot css and we'll start by just giving every cart item a margin on top just so we have some spacing let's do three m's and make sure that i actually include that css file so import dot slash cart item dot css and there's a margin showing up there it is okay now what i'd like to do is make these individual card items display in a row so i'm going to use flexbox once again on the parent div so each card item has a div the class name of cart item we've just been styling that i'm going to give it a display of flex once again if you need some flexbox help check out my flexbox youtube video it's uh i think it turned out pretty well anyways i'm going to justify content space between this is kind of a rough way of accomplishing what i want it's obviously not it's not beautiful and we have a couple of issues where things are moving around i'm going to give each div inside of a cart item so every child i'm just going to give it a width of 25 percent so they should take up all of that space now and be a bit more even but it's still not perfect you'll see things move around i think yeah there we go you can see this shift a little bit here um it's fine this is not really the focus of the video and we can style the buttons if we want um sure cart item button let's give it a width of maybe 30 pixels height of 30 pixels a background color of what did i do e 1 e 8 e e is that right i think so a border radius to make them a little bit curved same thing as the parents cart container six pixels and then i'll give them a little bit of uh margin to do top zero and then or top and bottom zero three pixels left and right okay so now we have a bit of spacing and uh that's fine enough um can also get rid of the border border none okay so there are the basic buttons and there's our grand total showing up down there um we could move that if you wanted to we could align that to the right hand side but i think this is good enough oh one thing i would probably do is make it clearer that a button is disabled right we're not styling it really it technically the default is that the text is slightly grayed out but i'm going to make the button grayed out so i'm going to select cart item button disabled which is the pseudo class wait pseudo class or pseudo yeah pseudo class when it's disabled um and what should we do here let's just give it a different background color a lighter background color i think i settled on f8f9fa is that right it's just a light very light gray and yeah there you go now that one is disabled now it's not okay not that it really matters but i think i might make this a little bit larger and give it some padding so that border has a bit more space between it so that's our cart css our cart title maybe padding bottom maybe one more m and then i guess that's good enough maybe font size will be a little bit larger let's do 24 pixels sure i don't know why i'm mixing pixels in with m's there why don't we just do like 1.5 ms and see how does that look okay that looks pretty good so that's our basic cart component i really just wanted to illustrate this pattern of having a stateful parent that renders stateless children or child components so a stateful cart component where we have functions that will update our single function that updates the state and then we pass down the state from this parent component as props to child components you're probably sick of hearing me talk about this but this is essential in react so this happens all the time in fact you often will pass state down as props more than one level if we were to really build this out we might add in a couple of features to a cart item if you can remember the home depot example we had three different shipping options that could be its own component and if you clicked one of those options we would want to update the state of the parent's parent the cart is keeping the state so we might pass down a function multiple levels of components and this was also an opportunity for us to talk about using map the array method map to generate lists of elements a bunch of cart items or a bunch of images or links or whatever based off of an array and we also talked about the correct patterns for updating state and not mutating arrays or objects and going out of your way to make sure you're not mutating any of those reference types which can often be a little bit of a burden in react but you get used to it and it's also a requirement if you want to work with things like redux so the last thing we'll do here is incorporate some local storage persistence so it's kind of silly for this example but it allows us to introduce a new hook other than use state which is called use effect so here's the end result it doesn't look any different but as i increment things let's do something obvious we have nine taco seasonings and six pinto beans as i refresh the page manually that persists nine six and one are still there we're not using our default initial values now if i look at my local storage local storage you'll see that we have our items in there and as soon as i change something let's say i go up to two for what are these sour two sour creams if i look at local storage again you'll see that it now reflects that change might be hard to see in here where are you come on all right why not change something more obvious i'll change taco seasoning it starts right now as nine let's go up to 10 and you can see that it shows quantity is now 10. so whenever the state is changing i am updating the value in local storage and if i reset local storage by clearing and i refresh will now go back to using the default two three and one so if we don't have anything in local storage we'll use that all right so to do this we need to use a hook called use effect use effect is new and react as part of react hooks and it allows us to specify some code that should run when a piece of state changes or when multiple pieces of state change or on the very first time a component renders or every subsequent time a component renders there are many variations in how we can use it but i'm going to show you the most basic syntax the first thing we need to do is import use effect and the way that we use it is by calling it and passing in a callback function so again there are multiple ways of well this is always the case you always pass in a callback but there are other things that you can do in use effect it's very useful but it takes a little bit of time to learn this is another one those topics that i spend a couple hours time well maybe like an hour and a half talking about uh in one of my react courses anyway so we passing a callback here uh and i'm just gonna do something silly like console.log hello from your effect and if i don't do anything else just hop over here and i open up my console let's see what happens we see hello from your effect the very first time my component renders and now every other time it re-renders we're seeing hello from your effect okay so it's a way of running some code at least in this case any time our component re-renders but how is it any different than just console.logging hello from your effect right here it really isn't but what is different is that i can pass in what react calls a dependency array or a dependency list which can be certain values from the state so for example items if i specify items right here this code is now only going to run this callback will only run if items changes now the thing is we don't really have anything else in our component that would cause it to re-render we don't have other pieces of states but we could i could make another one really quickly just to demo this const how about just count and then set count equals use states we'll just have one be the initial value and then down here i'm just going to make a little button that displays count and then when you click it we're going to call set counts i'll do an arrow function set count to be count plus one okay so let's just make sure that works there's my button and if i click okay it's updating that piece of state but you'll see over here that i'm not getting hello from your effect because i added items as the only dependency to this use effect or to this effect that i've set up so this function the callback will only be executed if items changes and so far it has not changed i'm updating a different piece of state but now if i change items by incrementing one of the quantities we get hello from your effect so that's a very quick demonstration of what this dependency list does there are other use cases for example if you pass in an empty array your effect will only run on the very first render but we're not going to do that right now what i want to do is instead of console.logging hello from your effect i want to actually update local storage so i'm going to call dot window.localstorage.set item and i'm going to set i guess i'll call it items it's a property and i'll set it equal to whatever items is so if items changes i'm going to set a new value in local storage there's a couple of issues with this approach but let me just show what happens there's no error or anything but if i look at local storage right now it is just a bunch of object objects inside of array brackets and that's because i need to turn this into json first so i'm going to call json.stringify of my items and set that in local storage and now we should be good to go anytime items changes if we look at local storage it's now updating uh let's see quantity here is set to four for taco seasoning i increment that to six we look at it now and it goes up to six okay so again the reason for using use effect rather than just setting window.localstorage every time it renders is that i can selectively update local storage or do something else i could make an api call to load data or to save something to a database only when one piece of state changes and in a more complicated component with more pieces of states that can be very useful so i'm going to get rid of this count stuff we don't really need it here and we're almost there except for the fact that our component is not using the values from local storage it always resets back to two three and one even though local storage is updated so what i'm going to do is instead of just using my initial items right away that have been passed in as a prop i'm going to look in local storage to see if there are any items in there if there's anything under the key of items so window dot local storage set this to a variable const initial state equals window dot local storage dot get item called items and that's going to be a string so i need to parse that so i'm going to do that here json.parse and then i can't just pass it in directly as initial state i mean i can and it will work if something's in local storage but if nothing is in there we'll have a problem so i'm going to just say initial state or initial items which is the prop that's been passed in so parse anything from local storage if you can find it use it if not if this is falsy then we'll use our initial items so at this point if i refresh let's see what we end up with here two three and one i'm going to increment uh how about we go up to 10 there and refresh the page and it's persisting 3 10 and 1. let's go up to 10 on all items okay refresh the page i'll do a hard refresh that local storage is persisting now if i clear that local storage dot clear and i refresh the page now we go back to two three and one we're using the defaults but now every subsequent time we go back to whatever is in local storage okay so that about wraps up the main concepts i wanted to cover here i know there's a lot a lot more to react that we could talk about i mean just with use date or just use effect uh there's so much more to discuss but this is a basic overview of the most common stuff that you need to know if you're working with react and with hooks all right we made it that was a lot uh we covered everything from what is react all the way up to uh styling it and using the use effect hook the state as props pattern they use state hook of course a lot of stuff and and we've covered most of the very basics of react but there's still a lot left this is not a comprehensive youtube course as i mentioned early on i have a 30-something hour course just on react so there's a lot to talk about or a lot that we could talk about but this should give you the basic tools that you need to go on and figure the rest out if you're interested you can take a look at my react course and then also the job guaranteed boot camp i mentioned at the beginning my online bootcamp course covers a lot of react and redux and thunk in addition to things like node and python and a whole bunch of javascript databases sql writing your own orm tons and tons of projects but there's a lot of react that's the point a lot of react and redux anyway you can check out the link in the description so thanks for watching everyone i hope you're all doing well staying safe uh and honestly i don't know if anyone made it to the end of this video i don't know who you people are who watch these two to three hour videos but if you're if you're out there uh i hope you enjoyed it and i'll be back later with some more videos have a great day night and uh i don't know i just gotta stop talking okay goodbye
Info
Channel: Colt Steele
Views: 97,834
Rating: 4.9823375 out of 5
Keywords:
Id: 9U3IhLAnSxM
Channel Id: undefined
Length: 138min 46sec (8326 seconds)
Published: Thu May 07 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.