Getting Started with React.js Tutorial for Beginners (v17 2021)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Hey guys, this is my first ever YouTube video and I decided to make it on my favourite front end framework. If any of you are just starting to learn React, I would love any feedback you have if you get time to watch the video. Thanks!

πŸ‘οΈŽ︎ 3 πŸ‘€οΈŽ︎ u/jamesgrimshaw πŸ“…οΈŽ︎ Feb 03 2021 πŸ—«︎ replies

thanks a lot dude

πŸ‘οΈŽ︎ 2 πŸ‘€οΈŽ︎ u/houssemaydi πŸ“…οΈŽ︎ Feb 03 2021 πŸ—«︎ replies

Great start! Excellent teaching skills.

πŸ‘οΈŽ︎ 1 πŸ‘€οΈŽ︎ u/vikkee57 πŸ“…οΈŽ︎ Feb 04 2021 πŸ—«︎ replies
Captions
hey and welcome to this beginner's guide to react js in around an hour or so i'm going to try and teach you all the basics of react so you can get up and running in your own projects this guide has been updated for react 17 and it's all based on hooks and functional components if that's important to you so let's get started so what is react route was created by facebook in 2013 and it's a javascript library for building complex user interfaces so yeah it's a library not a framework uh reacts to technically extends javascript and therefore it can be used as heavily in your application as you want so you could just use it in a small widget or of course for the whole site if you'd like to um as i was saying but although these days react does have a huge ecosystem around it meaning react can essentially be a complete framework if you wanted to if you used it with a build tool chain and an npm and so on but if this doesn't make any sense to you it doesn't matter reacts is not necessarily though for simple user interfaces due to its quite large overhead a simple website with some interactive buttons and animations can easily be made with just vanilla javascript or plain javascript so don't learn it for the hype if you don't understand javascript already or you're new to web development this is not the right place to start you should definitely start with vanilla javascript and any site that you can make in react you should be able to also make with vanilla javascript so over vanilla javascript reacts has three main advantages um or you know three main power moves i guess these are the virtual dom jsx and components so virtual dom if you have um a button on a page that you click and it changes some text for example or you have a counter react only re-renders that individual part of the page it doesn't re-render the whole page which is a huge performance improvement especially on large sites next is jsx jsx is the way that you actually render the visual components on the screen and it's almost identical in syntax to html which for people who are very familiar with html this is a massive reduction in the learning curve and it's really really nice to work with and finally components react is built around components which means you need to split your site up into loads of tiny different files and for large sites this hugely promotes reuse of code and also allows large teams to be able to easily work on the site with with little pain and finally it's incredibly popular which is definitely a plus for some people there's loads of available jobs and it has a huge ecosystem around it and community which can really help for getting started so of course this is not for beginners so what prerequisites wise you really need to be familiar with javascript javascript really is it's an extension of it you know it's for people who have outgrown javascript are looking to advance their web development career it's definitely not a starting point of course html css css i mean technically not required but html absolutely um a basic command line understanding would be a massive plus we're going to be using node and npm in this but i won't be going into it in detail so as long as you're familiar with you know um you're familiar or have used node once or twice before or npm and you think you know things like cd change directory etc um then you're more than qualified and of course familiarity and use of a text editor i use visual studio code it's my favorite but of course sublime text anything like that and finally a modern web browser so chrome or firefox is an absolute must so let's get started with installation how do you use react.js so since it's a library you could just use it with script tags you can include a couple of script tags on your page and then use react via the react and react on globals directly in your html file which is a really easy way to get started if you just want to play around with it or you can also use it by codepen or something if you google for that but in this tutorial we're using the most popular way of using react which is create react app you may have heard of this before but it is a tool chain for react so essentially um you will create a react app using a little command line um snippet and then what i'll do is it'll create a project with an entire file structure which makes it really really easy just get started writing react code and when you're finished it has built-in scripts for um building the final thing for production and it will create minified html css and javascript files that you can upload to any static web server so really really awesome and that's what we'll be using so let's get started okay so to install react we need to use create react app as we said now in order to use create react app we need to have node.js installed which you can check by running node v and if you get return with a version number you have it successfully installed and if you don't have it installed you can just head over to a web browser search for node.js and download whichever the current version is then go back to your terminal and check it's all successfully installed alongside node comes something called npm node package manager and mpx now npm will let us install dependencies for our project as you sort of get into reacts more you maybe install axios or some form builder or other plugins um but mpx is like a node executioner that will let us actually install packages onto our system um and in this case we want to install the create react app sort of boilerplate sort of build tool chain and we can run this uh by using the mpx command so before we do that we want to navigate into our working directory so in my case i want to work in this folder called youtube which a little neat trick you can do on mac is cd and then i can actually just drag this folder and it'll change my directory but however you need to do on your operating system just move to the directory you want to work in and now i'm going to run the command so mpx create dash react dash app is all you need to write create react app is the binary we want to install and the mpx this is the command and then the third argument here is the name of your project um so i'm going to call this one hello dash world and there we go press enter and it's going to create a folder inside of youtube called hello world and uh add all of our create react boilerplate code in there sorry back when this finishes okay great so it's also installed successfully um so the only other command we'll be using here in this tutorial other than maybe installing packages will be the mpm command to actually run the development environment for this so that is npm space start and this will start up our development environment oops so i'm not in my i'm not in the correct directory here so i actually need to move over first to my new hello world directory which i'm going to do by cd hello dash world and now i'm inside my actual react project so now i can run npm start and that will run one of the react scripts and open up in a web browser and there we go here is our react application all installed and working okay so now that react is installed and running on your system the next step is to open it in your code editor of choice so in my case i've opened the hello world folder inside of visual studio code and now we're going to have a quick run through of what files have now been added so um you'll be able to see um three folders and four files hopefully unless create react tap has been updated since you're watching this um and the our main folders that we're concerned with is public and source most this other most these other items here are automatically generated and aren't really of concern but we'll go through all of them anyway so read me this has just got some basic information about some of the scripts and just some nice information that's published onto github if you do put it on github and it may be nice to read through this to understand a little bit more about what create react app does package.json this is where all of your dependencies are described so we'll see that right now our project depends on react and react dom and more will be added here in the future when you add more dependencies maybe axios or something else package.lock is for locking in versions git ignore is a github specific file if you're not familiar with git it doesn't matter you can ignore this one our main concerns here are public and source so inside the public file um there's a whole bunch of files in here and you'll be familiar with these ones if you've obviously familiar web development so there's an index.html file here and this is well essentially what the result will be once you've compiled all of your react code so because rats creates a single page application i.e javascript does all the interactions and there's only actually one html page you will see here that there is some basic information here in the head some meta tags and other things like this there are some descriptions not all this is basic stuff and then there's this here div id root now this is important when the wrapped app is compiled all of the code is inserted into this root and then javascript handles everything that goes on inside here so javascript will generate the html code to go into the root and then the react app will all take place within here the next folder we're concerned with in here is the source folder so this is the main part of the folder structure here this is where all of your react code will actually live so the only two important files in here is actually index.js and app.js the rest of these some of these are actually completely unnecessary or they're a little bit out of the scope and you probably will not use them for a long time for example testing web vitals this is a new feature um the logo this is a actually the logo that is displayed here so many much of this will actually be deleted as you write your own code so what i'll do is i'm actually going to ignore all of these and in the next section we're actually going to delete all of this stuff and just keep some of the main parts here index and app so index.js first so this thing this file will actually be pretty much untouched so what it does is it uses react dom to take the app this means the all of the react code the app file here which we'll see in a second and insert it into that root div element that we saw in index.html that's all this does so react dom is basically the way that react code is transferred into the dom and that's why there's one individual file for this and then all we have to do is include our app component this is actually a component which is this file and then this function will put this into our root element for us and therefore we can actually pretty much ignore this file where all the real stuff happens is in app.js now app.js is where you'll start to see where things are falling together here this is the user interface that we see here with our rotating image and edit and save to reload here this is all this and as you can see this looks almost identical to html but this is actually jsx as i mentioned in the slides and this is where we're actually displaying our user interface we'll get into all of this in the next section okay so rendering in jsx so this section right here as we explored in the last section is actually jsx and not html so while it does look and act almost identical to html there are a couple of noticeable differences so class name up here in html this would just be class for example if you wanted to add the class name of app for your css but because class is a reserved keyword in javascript we use class name using the camel case um syntax here but the cool thing of course about jsx is because it's javascript we can write javascript just directly in here so for example let's say up here in avar this is our javascript function let's say we have a variable called name and i'm going to put my name in there james now this here in html this would be it'd be difficult to put this variable in here we'd have to you know identify by an id and then insert it into the inner html but it's simple here so all we need to do is add two curly brackets to say we're going to write a javascript expression and then we can just write javascript so i'm going to write name and that's literally it if we go back to our web browser here we'll actually be able to see that it's automatically reloaded for us and i've got my name appearing up here and i mean much of the other things you could change in here would act as you would expect so let's say i delete all of this and wrap this name in h1 tags like so just like in html this is acted exactly as we expect it to since you can add curly brackets and therefore write javascript code anywhere inside of jsx this would also work for attributes which in reacts are actually called props so for example if we had a class name that we wanted to add to this h1 but we wanted it to be dynamic for whatever reason what we could do is we could add the class and of course we're calling it class name and then equals and then curly brackets of course because we want to add some javascript code and then we can just reference the variable as you would expect and now this h1 will have the dynamic class name of my variable so if we go back to our web browser open up dev tools take a look at our inspector here and i'm just going to have a look we'll see that our h1 here has the class of james and it's working perfectly so that's your sort of rundown of jsx and we'll certainly get more into gsx into the next sections as we look at components and so on okay next is components so components are one of the most important parts of react and they are used for splitting up your user interface into smaller chunks that can be reused and also easily worked on by other people if you decide to grow a team in the future there are two main types of components in react these are called functional components and class based components now this tutorial is for react 17 and i personally no longer use class-based components at all since everything now can be achieved with functional components so this won't make any sense to you if you're new to react so you can just ignore this but if you are familiar with older versions of react i will not be covering class based functions now the function you see here is a functional component is what is called and it is created simply by declaring a javascript function in this case it's called app and then returning something and that return needs to be jsx so in this example you know that um html looking syntax right here and that creates a react component that is what a react component is before we continue what i'm going to do is i'm going to clean up a little bit the create react app boilerplate has added quite a lot of stuff a little extra code that i'm going to remove to avoid any confusion so first i'm going to delete this logo up here and save that and then i'm going to go to index.js and remove some stuff so we don't need report web vitals and therefore don't need this import here and we can therefore also delete a bunch of extra files here so i'm going to delete uh app.test.js logo.svg reportwebvitals.js and setup tests i'm going to go ahead and just delete all of those now if we save this and refresh we should still have a nice working page where we can continue from so a component this here is a component and um let's actually create a new component so let's say we have our header here with a name in it and i'm going to just create a paragraph here and add some text welcome to my blog so now we have james and welcome to my blog now i want to split this user interface up and make this james title into a new component so i can say reuse it on other pages or include it multiple times on this page so it's simple enough to do i'm going to create a new file in my source folder here and i'm going to call it a header dot js as simple as that and then inside of here i'm just going to create a javascript function so function and then because this is a component you'll notice how i've given it a capital h in the file name up here and i'm going to do the exact same here in the function so it has to be a capital letter like this if you want to do two words you would have to capitalize both words for example like this but i'm just going to call my header so i'm going to leave it like that and then of course it's a function i'm going to have two brackets and then my curly brackets here now as i said to make it a react component we have to return some jsx so i'm going to return and then i'm going to add some my h1 tags like i had before and i'm just going to say james like that now we're almost done what i'm going to do here is i'll just export this function export default header and that's it that means we have created our function and we export it as default function and that means that when it's imported into app here react is going to know that it is a function now again if you're coming from older versions of react or if you're not using create react app you'll actually have to import react up here in order for it to recognize that it's a react component by doing import react from react as simple as that however if you're using create react app in react 17 this has been made automatic now it'll automatically import the parts of react that you're using so we don't need to actually include that at all if we're doing a basic component that just displays some text here so back in our app what i want to do now is i want to actually use this component and show it inside of my main app component here so of course i want to replace my h1 here so i'm going to remove that and i'm going to go ahead and reference it here and the syntax for doing this is like a html tag so i'm going to open up my less than sign write capital h for the component name header and then make it self-closing so that's a forward slash and a more than sign to look exactly like this now this is underlined it's underlined because as it says here header is not defined this plugin here is called eslint by the way if you're interested you don't need this but it will certainly help as you get more into react so we need to import it in order to use it so we want to import capital h header the component name of course we want to make it available here and then we want to put from so we can say what file header is located in and then we just need to include a reference to it so we're in the same directory and it's called header.js so we have to do dot slash for the same directory you always have to do this if you don't do this reacts will be confused in terms of the path so this means current directory and then capital h for header now it's a js file but because we're in a js file already we don't need to put js on here this is redundant react will recognize that it's going to be a js file and automatically place it there so we can save that and go back to our web browser and just hard refresh and we'll see that it is working just as before so there we go we've imported another component into our file now here's something interesting so in our app.js file here we have this variable name and let's say that we have to store it here we can't store it in the header file because we use it multiple times on this page and we get it from a database for example we can't just you know write it in here statically like this so what we need to do is we need to pass in information to this header component so the way we do this is through something called props which looks like a html attribute so just like you would declare a html attribute you can put in the name of the prop that you know whatever you want to call it so i of course want to call it the same as the variable name here so i'm going to call it um you know name or in fact no i'll call it title so you can see the difference here so i'm going to call the prop title and then i want to pass data into the title prop that i'm sending to header which is going to be of course this variable name so i'm going to copy that open up my equals here and then of course we're writing a javascript variable so it's going to have to be curly brackets for that javascript statement that i explained earlier paste in name and there we go we've passed in a prop called title and made it equal to the variable name now if we go into our header how do we receive this whenever you have a component like this inside of these brackets here these parentheses there's always the variable props available this could be an empty object but in this case because we have passed a prop it's actually available that means that the props available on it are keys within that object so as you would if you were displaying a variable we want to open up our curly brackets to write a javascript statement and then we want to do props and then access the name key on the props object so that's going to be props dot name or sorry actually is props.title because we called the prop title even though the variable we passed in his name the prop this prop name right here is what you're actually receiving that's really important so i'm going to save that and go back as you can see we're still seeing the same thing which is working perfectly we're seeing our information through there and that's essentially it that is components and props we're going to see much more components as we get through and into the example near the end but that is the sort of basics of components and props okay so component state now component state is the coolest part of react this is why you actually use it over just vanilla javascript all the component stuff that we've done so far this is all kind of possible in javascript and quite easy to do state is essentially a variable that react listens to or jsx listens to that's sort of the best explanation for it without getting too technical it's going to be a variable that the user interface or jsx is going to listen to changes and display those changes so let me kind of give an example here let's say that we have this name called james now what i'm actually going to do is i'm actually going to make it like a login system so i'm going to say guest here so if we refresh that and go to here we'll see it says guest now i'm going to add a button down here so this is just a normal html button and i'm going to say log in just like that now here's where we're actually going to start learning about some javascript event handlers as well and how they work in react but as you would in normal javascript you'd use an on click here um on click in jsx is on click but with a capital c like that simple as that and then i'm actually just going to reference a function here so i'm going to make a like event function here as you normally would in javascript and i'm going to say it is function um login just like that and i'm going to reference it by doing just login you don't want to put brackets on the end of here because that means it would run automatically if you don't put brackets on the end then this will only run when the on click handler is actually clicked and it won't automatically run that wouldn't be good so that's pretty simple now inside of our login event handler here what i'm going to do is i'm just going to change the value of that variable so i'm going to set it name equal to james to simulate a sort of login event there now of course a const is not correct because i'm changing it i'm going to change that to a let and there we go this would be you know what you would expect to work right but if we go over to firefox here click the login nothing actually happens and this is where state comes to the rescue so state is essentially going to be we're going to change this variable of name to a actual piece of state and what's going to happen is the user interface over here is going to listen for that change and it's actually going to automatically update it when we click on the login button so let's do that how do we convert this to a piece of state well it's actually really really simple so there is something in react called a hook and one of those hooks is called use state it lets you hook into react uh use features from reacts if that makes sense so what we need to do is first of all import that so it is a named export from react it doesn't really matter if you don't know that means but that means that you have to put curly brackets here in the first argument of the import and it's called use state just like that curly brackets and then use state and that is from the react library super simple now now we can write the actual state syntax so state syntax looks like this it's a constant variable and then you need to put two square brackets like this and then these square brackets it takes two arguments a getter and a setter for this piece of state so the getter for me is just gonna call it name i just wanna be able to reference it by name like i already have and i need to create a setter now the setter is actually a function which is quite cool so in order to update this piece of state update this variable that we're storing we're actually going to run a function to do that so we can call this function whatever we want um the general naming convention here is just like set and then the variable so set name in a camel case like that and then we set that equal to this use state hook up here use state and this uh hook here is an actual function of course we uh we're running a function in order to assign these now what goes inside of this function call here what goes inside here is actually the default value of the state so so far we've made a getter and a setter for the state but we haven't actually given it a default value so it would actually just be you know undefined in order to give it a default value this event value could be anything you know an object an array a string in this case a string so i'm going to call it guest which works right so what else we have to do here to make this work so name and all this will actually already work right because our getter is called name like our old variable was great it actually still works but login doesn't as you can see it crashes so well you may guess we're going to run this set name setter so instead of name equals james we're going to run set name and of course it's a function what do we put in the function just the new value so james and there we go we've run the setter and we have obviously uh passing name here into our header and so on but we're using the getter and the setter and if we save that and go back over here press login there we go our user interface listens to that change and actually changes it to james and as i explained with the virtual dom earlier the page only re-rendered that singular word the whole page didn't actually re-render which if this was a very complex site will be a huge efficiency improvement so that state all right component life cycle so component life cycle is referring to the stages which the component takes in its sort of life and death as you could say so it's mounting onto the dom and then it's mounting off the dom eventually when you're finished with it so when we talk about lifecycle we're talking about lifecycle methods because we'll often want to run code when the component initially mounts onto the dom this is sort of the main use case here now that probably doesn't make any sense so let's sort of put this into an example where you could see why lifecycle methods would ever be used or why you would want to use them so of course we're making a blog here as our example has sort of come to b so our blog would need posts right we need to have a list of posts in our blog now if you were doing this making your own blog you would have a database and um therefore you'd display things from a database maybe from an api but in this simple example we're just going to use something called json placeholder which is essentially a fake api that we can use to well in this case display how react can work now on the when our component mounts here what we're going to want to do is we're going to want to make an api request aren't we because we can't make an api request until the component has actually mounted onto the page but we do want that api to request to happen immediately as soon as the component is mounted and we only want it to actually happen once so what we're going to do is we're going to use the use effect hook which runs code when the component mounts onto the screen now how do we do this let's first of all import it so just like we imported use state let's import use effect and to use it we actually have to run a function inside of our actual component here so where i place my use effect hooks are underneath my state so i put my state up here then i run my effect hooks and then i run my normal functions just here so let's do it use effect and use effect of course is a function but it takes two parameters it takes the actual effect callback the code you want to run um as part of the component mounting for example and the second is a dependency list so why a dependency list what does that mean a dependency list is um where the function is going to run as part of a dependency or as a reaction to dependencies so use effect hooks can be used for more than just when the component mounts the code can actually re-run when a piece of state that it relies on changes so an example could be let's first of all put a function in here as our first parameter so our function is going to just run console.log hello world like that and then our second parameter here is going to be our dependency list now this is an array of course it's a list of dependencies and if we display no dependencies here this just means run once run when the component mounts and never run again so if we save that go to firefox and have a look we'll see that it ran once when the component mounted and it's not going to run again so this is a perfect use case for our api fetch where we want to fetch posts we can just run our fetch in here and then it will we can store that in a state for example but what use effect can also do is it can also re-run if a dependency changes so what's that so if you had hello world and i want to say hello plus append on name from our state here we'll see that this is actually underlined which means it's missing the dependency of name for example if i didn't do it it would just run once for hello guest and in some situations it can actually cause huge problems and memory leaks in this situation it's very simple but you would have to make sure you add the dependency of name and this is so of course it would run whenever the name changes now of course it doesn't actually change until we press the button but if we did press the button it would actually run that use effect hook again and update it with that new name so use effect huts can be used for more than just when the component mounts but that is the only situation we'll be using it in this example so let's remove that that's hello world and let's go ahead and make our api request so if we go over to jason placeholder over here there's a little bit of um snippet here for using the javascript fetch api it's a really really simple function i'm not going to be going into it and i'm actually just going to be stealing this code anyway and let's paste it in place of this console log now this example is taking to-do's i don't want to do that i want to take posts this is a essentially a list of fake posts i think they're laura mipsam or something all this does is convert it to json and then eventually console log the result let's go ahead and actually see that because i want to see what we get there we go so if we look here we get our an array of 100 and we actually see all of our different posts here and each post is an object an object containing a body an id a title a user id for this example we're going to keep it really simple and we're just going to output the title we're essentially going to make a list here on the page so well first of all what we're gonna have to do here so we're gonna have to store this somewhere now we're gonna store it in state as we did with our name so let's create another identical piece of state called posts because that would be a logical name for it and then let's create a setup for that set posts and let's of course use the state hook and what's our default going to be well it comes in as an array and we don't have any posts of course when the component initially mounts so it's just going to be an empty array now it's really important that it's an empty array of course because what we're going to do is we're going to output this list onto the screen and when it originally mounts we would want that list to be empty and then we could maybe check if the list is empty and say loading or something like that and then eventually when the api request is finished it's going to update the state and then the screen is going to automatically update with all that list of posts so we can see here how state and effect hooks work together to create this really awesome and really clean solution for managing component lifecycle here so let's do this let's set posts with that incoming json data and there we go that should work but we'll obviously not be able to see that until we have actually rendered our posts onto the page so let's do that as the final thing down here what we'd want to make is a simple list of items so we let's just make an unordered list like that and then how would we create a or how would we automatically render um an like how would we automatically render an array onto the page now in javascript the modern uh javascript we of course have the map function which um this is one of the reasons why um you need to be experienced with javascript or have some experience with javascript before doing this tutorial because map can be a little bit complicated to understand but i will do it here anyway so posts dot map and as a quick explanation of what map does is essentially it is a function and it has a callback within it and the callback runs for each item in the array so i'm going to use a an arrow function here which has an automatic return on it and therefore i'm going to write post because this callback runs for each item so therefore it would call back an individual post for each loop or each item in the array sorry and what we want to do is we want to return jsx right and this is where jsx becomes really cool because because it's well it's just javascript we can actually just directly return jsx so of course an arrow function in one line is an automatic return and we can just output jsx directly there which is really really cool now because we've gone back into jsx again here what we'll then need to do is we'll have to add curly brackets again to say well we're in jsx here but we want to go back into javascript to output our variable now we know that post is an object because we saw that in the firefox an object but it has four keys on it we just want title so we're gonna do post dot title just like that again if you're not familiar with map um have a look at the javascript documentation and it should make sense but that's all we're doing is we're just looping through posts and outputting a list item for each item in the array and of course we'll be using this use effect hook to automatically update that list once the once the fetch call has completed so let's take a look at in action there we go if we actually refresh here you'll be able to see a split second where there's actually no items in the list but there we go that looks pretty good so you'll notice in the console there is just one little error here and this is to do with react and how it works with the map function so whenever you map out an array here and you're creating multiple different list items multiple different dom elements react wants you to identify each one just in case one individual one updates it doesn't want to over re-render the page or create any glitches so all you need to do to fix this is add a key onto the element that's been duplicated and give it something unique and most apis will obviously have an id for each post so let's go ahead and do post dot id and if we refresh that we won't see any visual change but we will see the error has gone because we have solved that small problem but there we go we're rendering out a list of blog posts and we're using the use effect hook to run that api request when the page loads now this section is titled event handling but if your keynote you'll actually notice that we already covered event handling when we did the login button however in react event handling can be a little bit more nuanced there are some scenarios that can create bugs and since this is a sort of full beginner's guide and you should be able to get started building your own applications you're going to quickly run into problems since event handling is a very core part of react the first example where this is quite a nuanced issue is for example if we want to pass in a parameter to login so let's say name is not statically written here and name actually comes from a parameter on login of first name and is therefore passed into name now if we wanted to you know supply this parameter inside of our on click here we would have to open our parentheses and type in you know whatever the parameter is but you're gonna of course realize the problem as i explained last time if you provide parentheses this will cause login to automatically run which of course is a huge problem let's show that let's save go to firefox and we're going to get two mirror renders it's infinitely rendering it ran automatically and it's going to keep running so what we need to do is we need to force it to only run when on click is run and we can do this by what's called binding it and to bind it all we have to do is run it within a arrow function now an arrow function is just a simple javascript function with a different syntax and all we have to do here is provide two parentheses and then an arrow equals and a more than and of course on one line just like our map here uh it automatically returns so we're just gonna put login there and that's all you need to do um of course this also allows you to grab the event which is really cool whenever you click there is an event automatically provided to you which you can grab by getting e here which is super useful so if you wanted to prevent a default action from happening in javascript or something else you wanted to get you know you know the input from a text field for example you can get the e by doing this and then of course pass it to your function if you wanted to but in this scenario we're just going to see how the arrow function fixes our problem and it does as you can see we refresh login works as before and it only runs when on click is clicked which is absolutely perfect furthermore through use of the arrow function here we could of course return not just an automatic return but we could return a block of code here to run inside this function and therefore we can actually run in more than once or we could run a different function here say you know a console log just like that and this is another really useful reason for using a arrow function here if i say refresh here log in button clicked we've run two functions at the same time let's do one more example just for good measure so let's say we want to add a new post to the top of our posts list and we want to have a button to do that let's create that so a button and it's going to add new post and of course we're going to have an on click handler which we're going to open up to our javascript expression and we're going to want to run our function now this function is not going to have any parameters so we don't need to run it inside of an arrow function we can just call it directly the function is going to be called on add post let's create that function function on add post just like that now of course we have two parts of on that post we're going to construct our new posts array um all we're going to do is add a new post onto the front of it uh and then keep all the other items in the array intact and then of course we update our state so that our user interface will update as part of it so you can kind of see how all of the parts of react are working together here so let's construct our new array we're going to be using some es6 trickery to do this some javascript es6 trickery again if you're not familiar with this stuff have a look at the documentation and it should explain it so i'm going to create all my new posts array so i'm going to call it new posts array and i'm going to create a new array so my square brackets and i'm going to add my first object this is going to be the new item i'm adding so it's going to have an id of 99 or 999 and then add a title title is going to be my new post and to add all the other items back onto the end of this array we're going to use the javascript spread operator which means i'm going to reference the existing posts array and just do three dots on the front to spread it out and essentially insert all of those items to the end of my array just like that now the only thing missing is to update my state with this new array that i've created which i'm going to do via set posts and just provide my new posts array as simple as that it's all that's needed so i'm going to go back over to firefox here press add new post and there we go we've added a new post it's really as simple as that so you can kind of see if you're creating a blog here um you could have a form and some text and so on i'm actually going to look at forms in the next section and you'd be able to press add new post and quickly update the interface react is really really nice to work with all right so forms this is going to be the last major section of this tutorial and we're going to explore how we can interact with form elements like in our case the input box as well as submitting forms and we're also going to explore a bit more about props because this scenario is actually going to pose a couple of different problems so let's get started so what we're going to do here the primary thing that we're going to do is we're going to change this add new post button to an input box and an add new post button and what you can do is you can specify any post title in here and we can add it to the top of the list so some of this functionality we'd actually already done so in our on add post function here we'd already created most of that functionality the only real thing we're doing here is this title needs to be dynamic based on some input from a text box and also it's getting quite complicated this app.js there's too much going on in here of course react is all about splitting your code up into components so what we need to do is we need to create a really a new component for this first so let's go ahead and do that let's go to our source let's add a new file and let's call it add post dot js and let's create our component here so of course like any other component we'd create a function here and we're going to call it add post now just as we called the file name notice the capital a capital p really really important to capitalize your components you can't go with camel case here that's not valid and of course some parentheses there open up our function and we need to return some jsx in order to make it a react component so let's return some paragraph and just say add new post form something basic and of course before we forget we need to export that as the default function so that reacts knows what to do with it so all done so let's go ahead and import this into here so as we did with our header we're going to import from and then we have an autocomplete here don't forget to set the current directory dot and forward slash and then we're going to reference it in our user interface now i'm going to replace this button with it and create some space here so we're just going to add post and self close it like that really nice so let's go to our firefox over here and there we go add new post form what's our next step um well let's go ahead and first of all steal this function it's no longer needed in the parent here in app.js but instead it's going to be needed here inside of add post this is going to be when we submit our full well and speaking of that well let's create our form so instead of paragraph tags we're going to create form tags just like that and inside of our form tags we're going to have two elements so these two elements are going to be an input and let's give that a type of text and let's give it an id as well let's give it an idea of post title let's go ahead and self close that and of course we're going to need a button to submit our form so let's create a button give it a type of submit and then we'll just create we call it you know add post something like that great so if we go ahead and i'm actually just going to comment this out this is going to cause an error because set posts doesn't exist there we go as you can see we have a text box and an ad post button and when we click the add post it actually refreshes the page because whenever you submit a form it actually automatically refreshes because it expects a url to go to so well let's start let's stop tying this together so a form of course has got a event handler on it and that's called on submit so kind of like a button has on click a form has on submit in normal html this would be on submit or lowercase but in jsx as the styling goes it's a capital s on submit just like that and of course we can set that equal to a an event here and we're not going to have any parameters on our function here on our post so we can just reference on add post directly like that if this had any parameters on it we would have to reference it inside of arrow functions like this but in our case we don't so on add post now whenever you have an event or whenever you have a function and event handle like this there's always the event available as the first parameter even if you don't have any parameters i'm going to abbreviate this to e and just like you would in vanilla javascript you can use that e to prevent the actual default redirects that we just saw e prevent default just like that now it's really cool we can actually test that our form no longer redirects add post does nothing press enter in here does nothing perfect so what are we going to want to do here well we're actually going to want to somehow record the value of what's in here because let's say we want to form our new posts array right here this title is going to be dynamic where do we get this from so in react whenever you have a form element let's say like an input what we want to do is we want to record the value of that input in the state and whenever it changes whenever you type a new character or delete a character we want to update that state and this is actually really easy to do so we use two props on the input element here which are value and on change now on change this is another event so we've now learned three events on submit on change on click on change is whenever the input value changes and just like any other change we get a e event on there so as you can probably tell here these perfectly align up to something we just learned about value that's a getter on change that's going to be a setter so we can align this up to state let's create a piece of state for it so const a getter and setters let's call it post title and set post title the getter and setup for our state and set that equal to use state and by default we want it to be an empty piece of text so let's just give it an empty string as a default value now of course we need to actually get use state so we're going to have to import it from the react library import use state don't forget the curly brackets it is a named export from react just like that and then what we can do now we've all done this is we can put our getter into the value now without unchanged we can't of course just put in set post title in here like well that's just going to do nothing right what does unchanged actually give us well on change like any other event hounder of course gives us that e that event so what we can actually do here is because it's going to give us a event and it's going to give us some information inside of it mainly it's going to give us what current text is in the text box so if we use an arrow function here just like you would if you were calling a function with a parameter we can get the e because this is a callback and then what we can do is we can set post title and of course because premises on here we have to use this arrow function syntax but luckily we need it because we need that event anyway now how do you get the current text in the text field from the event of course if you're familiar with javascript you will know that this is through e the target on that object and then the value e.target.value now that's looking good so how can we actually test this well first of all let's just go ahead and comment out this line because we're not just ready for it yet and let's go ahead and just output the value of the input just into some paragraph texture so let's just put post title into some paragraph text and this should actually well it's state so this variable here should just listen to the state changes so let's go back into here and let's start typing and there you go look at that what it's doing is it's actually listening to changes in the text box and then updating that paragraph as we're going so you can now see that whatever you typed into this text box is stored up to date in post title which now makes it really easy because now we can start generating our new posts array so let's go ahead and remove that and uncomment these two lines and pop in my title so our title is going to be post title now our last issue here posts and set posts we're in a sub component here so we don't have access to this getter and setter for a piece of state in the parent so where do we get it from well what we're going to have to do is we're going to pass it through as props so that's right you can actually send a function through as a prop which can actually make it really really you which is actually really useful especially if you're trying to pass through a getter and setter so let's go ahead and do that let's go to add post oh sorry let's go to app.js and let's pass in two props here the first one is going to be posts we want to send through that posts state as a prop called posts and we can set set posts and we can just send the function and if we send the function what we can do there is uh we can run the function and it will actually run it here which is really cool it's almost like rever a reverse prop so if we send over a function whenever that function is run it will actually affect the function in the parent which is really really cool so let's see that in action of course we'll need to get props and then both of these calls here will have to be props dot so they're getting off the props object simple as that so let's go ahead and test it let's type in my new post add post and there we go look at that it's added a new post let's add another one as simple as that now we have a little issue here of course we've added two new items to the array with the key of 999 here so this should be something unique you could just generate a random number here but i'm not going to worry about that one too much so there we go that is how you work with form inputs in react all right congratulations for making it this far through the tutorial i hope you found it useful but our application is pretty much done here so we've made a basic sort of blog i guess where you've got a list of posts coming from an api and you can add a new post you can sort of log in to change the state here just some cool little things i'm just gonna do a couple of little things to this just to show about other other parts of react and how some of the modern javascript features from es6 integrate with this so the main thing here is going to be a loading whenever the posts are coming in from the api so this is going to use something called conditional rendering so essentially here what we're going to have is when we have our list of posts down here at one point that list is going to be empty in javascript you have a statement that looks like this a true or false value let's say it's true and then you can do a question mark and then you can write what happens if it's true here value is true and then a colon and then value is false so this is a conditional expression here and we can use this sort of one line conditional to actually conditionally render things onto the screen and this sort of argument over here can actually just look at the value of state so example if we have our posts here and we're obviously already in curly brackets here what we could do is we could evaluate whether the dot length is either true or false so if the post at length is zero that's false and if it's more than zero then it's going to be true so we say post dot length question mark so that means if it's got a length then display posts which we've done but then if at the end of this if we put an otherwise i.e a colon then we could say something like loading and there we go that's how you do conditional rendering if we were to refresh the page you would see loading there for a split second and that's conditional rendering okay thanks so much for watching it's been really really fun teaching this um now i implore you to go and practice i really struggled learning react until i'd really tried applying it to my own project so for example i wanted to build a portfolio and it really wasn't until i actually got started and built that portfolio until i actually understood react at all i just thought i understood it by watching tutorials this tutorial has tried to address all the things that i found difficult learning so all the things that confuse me in tutorials i try to make it as clear as possible here thanks so much for watching and i'll see you next time
Info
Channel: James Grimshaw
Views: 2,507
Rating: undefined out of 5
Keywords: react, reactjs, react 17, react.js
Id: g0zalmyeu0c
Channel Id: undefined
Length: 59min 55sec (3595 seconds)
Published: Tue Feb 02 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.