React Tutorial for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] welcome to the ultimate react course in this course you will learn everything you need to know about react from the basics to more advanced concepts so by the end of the course you'll be able to confidently build fast and scalable apps with react if you are looking for a comprehensive easy to follow well-organized and practical course that takes you from Zero to Hero this is the right react course for you you won't need any prior knowledge of react to get started everything you need to know is right here so you won't need to jump back and forth between random tutorials now unlike other courses we won't be building a dummy App instead we'll be building and deploying a beautiful production grade app for discovering video games this app has all the features and UI patterns you would expect from a modern application we can toggle within the dark and light modes we can search for games filter them by genre as well as platform now as we change filters the page title gets updated dynamically we can also sort games and here we see loading skeletons while games are being fetched from the back end and that's just the start in the next part which I'm currently working on we'll dive into advanced topics like routing State Management fetching data with react query authentication error handling performance optimization and much much more I've put my heart and soul into creating this course and I'm confident that it's going to be a game changer for your react skills I'm Marsha madani I'm a software engineer with over 20 years of experience and I've taught millions of people how to code and become professional software Engineers through my YouTube channel and online school codebitmarsh.com if you're new here make sure to subscribe as I upload new videos all the time so if you're ready to master react and build front-end apps with confidence let's jump in and get started [Music] thank you [Music] before we get started let's talk about what you will need to know to take this course first things first you don't need to know react to take this course however you should have a good understanding of HTML CSS and JavaScript if you're comfortable writing code in these languages you are in a great position to start learning react now throughout the course we'll be using typescript typescript is a superset of JavaScript that adds static typing to the language essentially it helps us catch errors earlier in the development process which can save us time and headaches down the road now don't worry if you have never coded in typescript before I'll hold your hands and teach you everything from scratch with that out of the way we can dive right into learning react before we begin coding let's take a few minutes and discuss what reacting is and how it helps us create better applications react is a JavaScript library for building Dynamic and interactive user interfaces it was created at Facebook in 2011 and is currently the most widely used JavaScript library for front-end development so if you're looking for a job as a front-end developer you should know how to confidently build applications with react but why was react created well as you probably know when a web page is loaded in a browser the browser takes the HTML code and creates a tree like structure called the document object model or the Dom for short this allows us to use JavaScript and change the page content in response to user actions for example we can use JavaScript to hide an element when a button is clicked this is called vanilla JavaScript meaning plain JavaScript code without any third part tools now as our applications grow working with a Dom can become quite complex and challenging to manage this is where react comes into play with react we no longer need to worry about querying and updating Dom elements instead with this grab a web page using small reusable components and react will take care of efficiently creating and updating Dom elements so components help us write reusable modular and better organized code now let's look at a real word example imagine you want to build a web page like this on this page we have a navigation bar on the top a side panel on the left and a grid of video games in the main area we can build each of these sections as separate components now in this grid each game is displayed in a cart which is an independent component with a like button that's another component itself we can build all these components individually and then combine them to build this page essentially a react application is a tree of components with the app being the root bringing everything together all right that's enough theory for now next we're going to set up our development environment and get a feel for what it's like to build applications with react foreign foreign to take this course you need to have node version 16 or higher now to check the version of node on your machine open up your command prompt or terminal window and run node Dash V so on this machine I'm running node version 19. you might be running a newer version that's totally fine it's not going to impact the materials in this course but you need to have node version 16 or higher if you don't head over to nodejs.org and download the latest version on this page now in this course just like my other courses I'll be using visual studio code or vs code as my editor you're welcome to use any editor that you prefer but if you want to use vs code I strongly suggest you to use the printer extension for formatting your code so here's the extensions panel over here search for prettier and install this extension once you do that on the top under the code menu go to preferences and settings now this layout might be different on Windows or Linux I'm not entirely sure but find the settings dialog and on this page search for format on Save if you take this box every time you save a file that file gets automatically reformatted with all that now we are ready to create our first react application [Music] there are two ways to create a react app we can use the official tool provided by the react team it's called create react app or CRA but we also have another tool called Veet that's getting increasingly popular these days because it's much faster and gives us smaller bundle sizes so here in the terminal window I'm currently on my desktop to create a new app using Veet all you have to do is run npm create Veet at latest or if you want to use the exact same version as me which is what I recommend you because I want to make sure you have the exact same experience then you need to specify the version that is 4.1.0 okay now npm is asking if you want to install this package let's proceed next we need to specify our project name which is Veet project by default but we can change that to anything like react app next we need to select a framework so using meet we can create any kind of JavaScript project we can use vanilla JavaScript which is Javascript without any third-party tools we can also create a view project a react project and so on so using up and down arrows we can move down this list let's select react next we need to select a language so here we have JavaScript and typescript we're going to use typescript in this course good so now we have a new project next we need to go into this folder install all the third party dependencies and run our web server so let's set it into the react app folder and type npm install or npmi that is shorter and with this we can install all the third-party libraries all right now we need to open this project in vs code to do that we type code period if this doesn't work on your machine simply drag and drop that folder into vs code now here in vs code we can open an embedded terminal by pressing Ctrl and backtick if this doesn't work on your machine just go to the terminal window and open a new terminal you can also see the shortcut right here so this is our embedded terminal it's much easier to use this than switch back and forth between vs code and a different terminal window now to run our web server we type npm run Dev now this launched a web server at this address localhost Port 5173 this might be different on your machine so don't worry about that just open this address in your browser and this is our first react application next we're going to create our first react component so this is our project loaded in vs code now let me give you a brief overview of the key files and folders in this project here we have the node modules folder this is where all the third-party libraries like react and other tools are installed you'll never have to touch this next we have the public folder this is where the public assets of our website exist like images video files and so on next we have the source folder this is the source code of our application in this folder currently we have a component called the app component don't worry about any of the code here we're going to rewrite everything from scratch all I want you to note here is that currently in this application we have a single component called the app component now outside of the source folder we have index.html which is a very basic HTML template in this template we have a div with the idea of root that is the container for our application below that we have a script element referencing Source slash main.tsx this is the entry point to our application next we have package.json in this file you can find information about this project so we have the name of the project its version a bunch of script the list of dependencies So currently we're dependent on two libraries react and react on version 18. we also have a bunch of development dependencies these are only used for development they're not going to be deployed with our application in the future next we have a typescript configuration file here we have a bunch of settings for telling the typescript compiler how to compile our code to JavaScript now for the most part you never have to touch this file unless you're an advanced user and finally we also have a configuration file for Veet again for the most part you don't have to touch this file [Music] Now to create a react component we right click on the source folder and add a new file called message.tsx so the extension of typescript files should be either TS or TSX quite often we use Ts for plain typescript files and TSX for react components now there are two ways to create a react component we can use a JavaScript class or a function these days function based components have become more popular because they are more concise and easier to write so that's what we'll use in this course but if you're maintaining an older react project that is built with class components you can look at my previous react course to learn about them but function based components are the recommended approach for new projects so here we declare a function called message that pay attention to how I have named this function this convention is called Pascal casing with Pascal casing we should capitalize the first letter of every word in this case p and C it's really important to follow this convention because this is the convention that both react and other developers expect us to follow so in react application whenever we want to create a function component we should always follow Pascal casing now here we should describe what the UI is going to look like where we use this component so let's say wherever we use this component we want to render an H1 element with a message like hello work so here we return an H1 element with hello world now this syntax might make you a little bit confused you might be thinking that you're writing HTML code in the middle of JavaScript code but that is not correct this syntax you see here is called jsx which is short for JavaScript XML so this code under the hood is going to get compiled down to JavaScript if you head over to babblejs.io repo that is repl you can see how this code gets converted to JavaScript let me show you so on the left side we can write jsx code like H1 hello world and on the right side we can see the equivalent JavaScript code so this piece of code gets eventually converted to react.createelement the type of element is H1 and the message inside the element is hello world so this is a very basic component now to use this first we need to export it as a default object from this module now let's go to the app component and use this new component so back to our project here's the app component now we're going to delete everything in this file now let's create a new component called app now in this component let's say we want to have a div and inside the div we want to have our message component so first we need to import our message component from period slash message so period means the current folder now we can use this component just like regular HTML elements so we add the opening tag and close it it's really important to close it we should always close our react components or we'll get a compilation error now here we can also use the self-closing syntax that is more concise now just like the message component we should export the app component so it can be used somewhere else now here in the terminal you can see our web server is still running and here we have HMR which is short for hot module replacement so read under the hood monitors our files for changes whenever we make any changes it will automatically refresh our page in the browser so now you can see our message component rendered on the screen now this is a very simple example in a real world application a component can have Behavior so here we can have a button when the button gets clicked perhaps we can change the message we can do all sorts of things so with jsx we can easily describe the user interface of our application with HTML and JavaScript now the great thing about jsx is that it allows us to easily create Dynamic content for example here we can declare a constant Cod name I set it to my name Marsh now we can replace this word with my name dynamically so here we add braces and inside the braces we can write any JavaScript expression an expression is a piece of code that produces a value so here we can reference the name constant we can also call a function like get name basically any piece of code that returns a value so here we can add my name dynamically we can also write if statement so we can say if name is true theme return this markup otherwise return a different markup like Hello World now back to the browser you can see my name is rendered on the screen however if I change the name to an empty string we see Hello World so this is the beauty of jsx using this syntax we can easily describe the user interface of our applications [Music] So currently we have a component tree with the app being the root or top level component and the message being a child when our application starts react takes this component tree and builds a JavaScript data structure called the virtual Dom this virtual Dom is different from the actual Dom in the browser it's a lightweight in-memory representation of our component tree where each node represents a component and its properties when the state or the data of a component changes react updates the corresponding node in the virtual Dom to reflect the new state then it compares the current version of virtual Dom with the previous version to identify the nodes that should be updated it will then update those nodes in the actual Dom now technically updating the Dom is not done by react itself it's done by companion Library called react Dom so earlier we talked about package.json in this file we can see the dependencies of our application so currently our application is dependent on two libraries react and react on let me show you how these work together so in index.html I told you that we have a div with the idea of root and this is the container of our application below that we have a script element referencing main.tsx now if you look at this file you can see that here we're using react Dom to render this component tree inside an element with the ID of root so this is our component tree here is our app component that is wrapped by another component called strict mode this is one of the built-in components in react it doesn't have a visual representation its purpose is to identify potential problems so we're taking this component tree and rendering or displaying it inside an element with the idea of root and to do that we're using the react on library but we can also render this component Tree in a mobile app using a different Library called react native so react itself is not tied to a particular platform like web or mobile it's platform agnostic and we can use it to build apps for web mobile and desktop devices [Music] so you have learned that react is a JavaScript library for creating user interfaces in contrast to react we have other tools like angular and view which are Frameworks but what is the difference between a library and a framework a library is a tool that provides specific functionality while a framework provides a set of tools and guidelines for building applications so a library is like a tool while a framework is like a tool set now react is just a library or a tool for building user interfaces so the only thing that it does and is good at is creating Dynamic and interactive user interfaces but we hardly use only react to build modern applications we often need additional tools for concerns such as routing which means allowing the user to go from one page to another making HTTP calls managing the application State internationalization form validation animations and so now the great thing about react is that it doesn't have an opinion about the additional tools we should use for these concerns so we can pick the right tools for the job in this part of the course our focus is entirely on react and no third-party libraries once you master react in the next part we'll explore some additional useful libraries in the react ecosystem hey guys Marsh here before we dive back into the tutorial I just wanted to say that this tutorial is actually the first hour of my complete react course the full course includes eight hours of content jam-packed with the latest techniques and best practices it's got everything you need to become a react Pro including exercises summary notes cheat sheets and even the project I showed you at the beginning of this tutorial and the best part is it comes with a 30 day money back guarantee so if you're loving this tutorial and want to take your react skills to the next level I highly recommend checking out the complete course using the link below this video thanks for watching and now let's get back to the tutorial so you got a taste of building applications with react in this section we'll be covering the fundamental concepts in react applications this is the most important section in this course you don't want to miss the materials I've covered here help you build a strong foundation in react we'll talk about building components rendering markup with jsx managing State passing input to components where props and debugging react applications so let's jump in and get started [Music] all right in this lesson we're going to create a basic list group component first we're going to install bootstrap to give our application a modern look and feel now in case you are not familiar with bootstrap it's a very popular CSS library that gives us a bunch of CSS classes for styling our applications so here we open up our terminal window you can see our web server is running so we open a new terminal window and run npm install bootstrap the version that I'm using in this video is 5.2.3 let's go ahead good now we need to import it in one of our CSS files so here in the source folder we have a couple of CSS files one is app.css this file contains all the styles for our app component we don't need any of this stuff anymore delete we also have index.css where we have Global styles for our application again we don't need any of these Styles here because all of them were generated by wheat so we can delete this file entirely now let's go to main.tsx you can see that our index.css file was imported here we're going to replace this line with import bootstrap slash dist slash CSS slash bootstrap.css okay now to make sure that bootstrap is imported properly we go back to the browser so previously hello world was in the middle of the page and we had a different font now it's up here and it has a different font beautiful so now let's create a list group component so back to our project here in the source folder we add a new folder called components this is not necessary but by convention we put all of our components in a folder called components now here we add a new file called list group dot TSX again pay attention to how I have named this file here we're following the Pascal convention so we're capitalizing the first letter of each word now in this file with declare a function called list group for now let's just return an H1 element list group and Export this from this module next we need to import this in our app component so if you're on Mac press command and P if you are on Windows press Ctrl NP here we can search for files like app.tsx okay now we don't need the message component anymore so let's remove the slide instead we're going to import our list group com component okay and we're going to use that right here okay let's make sure everything is working up to this point so here in the browser we have our list group component beautiful now finally we need to display a list of items here and for that we're going to borrow some code from bootstrap so head over to getboosttrap.com go to the docs and on the left side under component section you should find list group so this is a list group component in bootstrap to create a list like this we need to use this markup so we need a UL with this class and a bunch of list items with these classes so we copy this we go back to our list group component and return this markup now here we get a bunch of Errors because class is a reserved keyword in JavaScript or typescript so here we need to rename all these classes to class name now let me show you another shortcut let's rewrite this back we select the class keyword now if you're on Mac press command and D if you're on Windows press Ctrl and d and with this we select the next occurrence of the selected keyword so now we have multiple cursors we can press command and d one more time and again and again and again now all of these are selected so we delete them and type class name then we press escape a couple of times to disable multi-cursor editing okay now finally I save the changes but my code is not reformatted so let's investigate why this is happening on the top Under The View menu we go to the command palette note the shortcut on Mac it's shift command and P and here we search for format document okay here we have an error saying there are multiple formatters for typescript jsx files so let's click on configure and here we're going to use prettier as our default code formatter good now this file is formatted Beautiful Just note that prelayer automatically wrapped our jsx markup in parenthesis this is necessary to break the markup into multiple lines so if you're not using vs code with prettier be sure to add the left bracket in front of the return keyword so you can spread your jsx into multiple lines so now back to the browser here's our list group component but this is pretty boring this doesn't have any functionality and it doesn't allow us to render or display these items dynamically so we're going to solve these issues one by one over the next few lessons [Music] now what if we want to add a heading here well if we add another element here like an H1 we get a bunch of Errors because in react a component cannot return more than one element so earlier I told you that this H1 expression that we have here eventually gets compiled to JavaScript so this line gets translated to something like react.createelement with H1 being the type of the element the same thing will happen for the second element so in this function we are returning multiple elements and this is not allowed in react now to solve this problem we have a couple of different ways one simple way is to wrap this entire expression inside a div or another element so let me show you another shortcut we select all this code then we bring up the command palette so we go to the view menu and bring up the command palette or better we use the shortcut and here we search for wrap with abbreviation now we press enter and here we specify the type of element that we want to use to wrap this entire code so div enter done okay so that's one way but we're adding one extra element in the Dom purely for making react happy this is unnecessary a better way is to use a fragment so on the top we import fragment from react make sure to put it in braces now we replace the div with a fragment so just like before I've selected the div element now we can press command and D to select the other div and now with multiple cursors we can edit both of them in one go okay now with this change when this component is rendered on the screen we're not going to have an additional element like a div in the Dom okay now there is even a better way to achieve the same result we have a shorter syntax we don't have to import the fragment component from react so let's delete this line and we select the fragment tags both of them and remove them so if you add empty angle brackets we're telling react to use a fragment to wrap all these children now back to the browser so here's our heading and our items beautiful [Music] now this list is kind of useless because we have hard-coded these items in our markup what if you want to render a list of items dynamically well let's declare a constant called items and set it to an array of strings here we can use the name of series like New York San Francisco Tokyo London and Paris now in jsx we don't have a for Loop so we cannot write code like four item in items render whatever it doesn't work that way so we have to use a different technique in JavaScript as you probably know arrays have a method called map for mapping or converting each item to an item of a different type so if you type items dot map here we can pass an arrow function we can say take each item and convert it to an item of a different type so here we want to convert each item to an Li element so here we type Li and inside the tags we want to render or display the item itself earlier I told you that in jsx we use curly braces to render data dynamically so here we render the item itself okay now we're going to delete all these list items and instead we're going to bring down this piece of code however we get a compilation error because this expression is not allowed in the middle of a jsx markup in jsx we can only use HTML elements or other react components so to render data dynamically we need to wrap this expression in braces okay now save the changes our code got reformatted so Predator plugin broke down our code into multiple lines and added parentheses to wrap them now back to the browser here's our list of cities beautiful while reviewing this video I just realized that I made a mistake earlier and forgot to apply a CSS class to our list items that's why we have lost styling here but don't worry I'll fix that in a later video however if we right click anywhere on this page and go to inspect this is Chrome developer tools you should probably be familiar with it here on the console tab we have a warning saying eat child in a list should have a unique key prop what does this mean well back to our code this is where we are mapping each item to a list item here the warning is saying that each list item should have a key prop or key property that uniquely identifies that item react needs this to keep track of our items so later when we add or remove items dynamically react knows what part of the page should be updated so when rendering a list of items using the map method we should give each item a unique key now in this case each item has a unique string so we can use the item itself as a unique key but in a real world application where we retrieve items from an API quite often each item has a property like ID we don't have that in this case so we don't have to worry about it now back to the browser let's refresh the warning is gone and here's our list beautiful [Music] sometimes we want to render different content based on certain conditions for example here we can add an if statement and say if items the length equals zero perhaps we want to show the user a different message so here we can return a completely different markup for example we can add a paragraph and here we say no item found now to make sure this works I'm going to change the constant to a variable so we can reassign this on the next line okay now back in the browser so here we have no item found beautiful but our heading is gone so we can come back here and add our heading as well list and now we need to wrap this entire expression inside a fragment so let's add a fragment okay now if I save the changes Predator reformats our code and here once again we have parenthesis for spreading this code over multiple lines with this our heading is back but I don't like this implementation because we have a bit of duplication and generally speaking duplication in code is not considered a good practice so let me show you a different way to achieve the same result we're going to get rid of the if statement instead we're going to render things conditionally inside our jsx expression however inside this jsx expression we cannot write an if statement because as I told you earlier here we can only use HTML elements or other react components The Only Exception is braces with braces we can render anything dynamically so here we can use the ternary operator in JavaScript so we start with our condition items the length equals zero then we type a question mark if this condition is true we're going to return a paragraph with this message otherwise we're going to return null meaning nothing will be rendered with this we have the same result as before and our implementation is a little bit more concise now sometimes this logic can get a little bit too complicated and it can pollute our jsx markup in those cases we can always extract this logic and store it in a separate variable or constant for example here we can declare a constant called message Now we move this expression right here and then we can simply render our message constant in our jsx markup so now our j6 markup is a little bit cleaner now we can also move this logic inside a function for example we can declare a function called get message and here I'm using the arrow function syntax now we can move this logic right here and now we don't need this constant anymore so here we have a function and we can call that function to get the right message now the benefit of using F function in this case is that our functions can have parameters so perhaps we can get different messages depending on different conditions so here we can pass different arguments like one or whatever and get a different message if you don't have that scenario it's better to use a constant in this case now let me revert this code back to the previous state I'm going to move this expression right here so I can show you a more concise way to write the same code so let's remove this function okay look this piece of code is fine and it works but the part that bugs me a little bit is the second part returning null here let me show you a better way to write this code we start with our condition items that length we call zero now instead of using the ternary operator instead of using a question mark we do a logical and between this condition and the value that we want to return if this condition is true that is the paragraph element okay with this implementation we don't have the null keyword and our code is a little bit more concise but how does this work well let's go back to the browser and open up Chrome developer tools here in the console tab this is going to be our JavaScript playground if you have a Boolean value like true and perform a logical and with another value like one see what happened the result of this entire expression is equal to the second value what if we type true and mosh the result of the expression is mosh now what if you have false and mush the result is false so what does this mean well that means if our condition is true the result of this entire expression will be our paragraph element but if the condition is false the result of the entire expression will be false and nothing will be rendered on the screen so this is a very common technique react developers use to render content dynamically okay with this we can remove the slide and this is our final implementation foreign [Music] now let's see how we can handle click events in a component first I'm going to remove this line so we bring back our items good now I just realized that earlier I made a mistake and forgot to apply one of the Boost trap classes to these items so back to our code this is where we're rendering a list item we should give this a class of list Dash group Dash item okay that's better now we want to be able to click on each item and see it on the console in react each element has a property or a prop called on click so here is that on click to braces now inside the braces we can write an arrow function so a function with no parameters and here we can just say console.log clicked as simple as that now I'm going to save the changes so the code is reformatted so now each property or each prop is on a separate line okay now back to the browser we had an internal server error from this web server don't worry about it just refresh error is gone now if we click on each item we see this message beautiful but what if you want to see the actual item that was clicked well look this is where we are mapping each item to a list item so when creating this list item we have access to each item because we are using that item as the key of each list item right so instead of logging clicked we can simply log item now if we click on each item we see it on the console beautiful and by the way when mapping items we can optionally add a second parameter as an index and with this we can see the index of the item that was clicked so let me show you I'm going to clear the console now if we click on each item we can also see its index in the array lovely now this Arrow function can optionally have a parameter that represents the browser event we can call that e or event whatever we prefer now let's log this on the console and see what we get so clear click look the type of this object is synthetic base event I know it's a fancy term this is one of the built-in classes in react because different browsers have different implementations of event objects so to make this cross browser react team have created a class called synthetic bass event that is a wrapper around the native browser event object now if you look at the properties of this object you see properties that you're probably familiar with for example we have client X and client Y which represent the position where we clicked we also have type which represents the type of event we have Target which is the element where I clicked that was a list item with this class now our event handling logic here is very simple it's just a one-liner so writing a function here is totally fine but if our logic gets more complex we don't want to write that logic here in the middle of a jsx markup instead we should move that logic into a separate function so in this component we declare a function by convention we start with the word handle and then we specify the type of event in this case click now we set this to let's grab this piece of code and paste it here now we have a warning from the typescript compiler saying parameter event implicitly has an any type so the reason I know this is a typescript issue is that here we have Ts that is short for typescript but why are we getting this warning well the reason we're getting this error is that the typescript compiler doesn't know the type of this parameter is event a number is it a string is it an object what is it so if we use the dot operator we cannot see any properties of this event object this is where we need to specify the type of our parameter so we get Auto completion and type safety so let's hover our Mouse over this event parameter look the type of this parameter is react.mouse event so when we pass an inline function here the typescript compiler knows the type of our parameter that is why we didn't get a warning earlier but in this case we're declaring a brand new function the typescript compiler doesn't know where we're going to use this so it doesn't know the type of this parameter so we should go on the top add import mouse event from react and then after the parameter we type a colon followed by its type this is called type annotation in typescript so we type annotation we can specify the type of variables parameters and so on now with this annotation if we use the dot operator we can see all the properties of this mouse event object this is one of the beauties of typescript we get Auto completion we get type safety and it's easier to refactor or restructure our code you'll see more examples as we go through the quest so let's finish this example so now we have a function here this function is called an event handler because its job is handling an event in this case The Click event now over here we're going to remove this inline function and simply reference our handle click function note that I'm not calling this function we don't want to call it we just want to pass a reference so you're telling react that whenever the user clicks on this event this function should be caught so calling this function will be done later at runtime now let's make sure everything is working so let's click on one of these items beautiful [Music] all right now the next step when we click on an item we want to highlight it to do that we have a CSS class in bootstrap called active so back to our code this is where we are rendering a list item I'm going to give this a second class called active now look all of them are highlighted or activated this is not what we want we want to highlight one item at a time to do that we need a variable to keep track of the index of the selected item so back to our component let's declare a variable called selected index we can initialize this to negative one that means no item is selected if we set this to zero that means the first item should be selected now down here we can render this active class dynamically so we're going to use the same technique you learned in the conditional rendering lesson so I'm going to remove the quotations here we add braces so we render content dynamically here we can check the selected index if it equals the index of the current item that means that items should be active so we're going to give it two classes list group item and active otherwise we should only give it the list group item class this is a very simple way to add classes dynamically there are other more Advanced Techniques let's not worry about them at this stage let's just see if this works or not so back to the browser now the first item is selected beautiful now when we click on an item we should change the selected index so this is very good handling the click event now in this case we need a simple error function to update the selected index so I'm going to get rid of this handle click function so we deleted from here as well as here we should also delete the mouse event import on the top okay so always pay attention to cleaning up your code so here we write a simple arrow function and here we set selected index to the index of the current item okay now back to the browser let's click on item nothing is happening why is that well this variable we have declared here is local to this function component so react is not aware of it it's like a little secret inside this component to solve this problem we should tell react that this component is going to have data or state that might change over time and to do that we have to use one of the built-in functions in react called use state so when we type this here and press enter it gets imported on the top okay now this function is called a hook a hook is a function that allows us to tap into built-in features in react so this is called the statehook we have other hooks that you will learn about as we go through this course using the state hook we can tell react that this component can have data or state that will change over time so instead of declaring a variable this way we're going to call this function that we're going to initialize our variable we can give it the initial value of negative one now this returns an array in this array we're going to have two elements the first element is going to be a variable like our selected index variable and the second element is going to be an updater function using that updater function we can update this variable and at that point react will be notified so it knows that the state of our component is changed and then it will re-render our component which causes the Dom to be updated under the hood so as I told you earlier in the course with react we almost never have to touch the Dom directly we think in terms of components that have state when the state of a component changes react will update the Dom to match the new component State okay now let's see how we can use this so instead of working with two individual elements here it's easier to destructure this array into two elements so the first element is going to be select an index and the second element is going to be a function which we call set selected Index this is a convention we follow in react applications so here we have a state variable called selected index and here we have a function called set selected index now as another example we can use the state hook to declare another variable called name so we call view state we can initialize the name to an empty string this returns an array which we can destructure into two elements name and set name that's the idea now in this case we don't need a name variable so let's delete this line and the comment and the slide so here we have a state variable called selected index now down here to update this variable we're going to call set selected index and give it the new index with this when we click on an item it gets selected beautiful so this is how we tell react that our component can have state that will change over time now one thing you need to know about component state is that each component is going to have its own state so if we go back to our app component and add another instance of our list group here each list group is going to have its own state so in our first list group Paris is selected but in our second list group nothing is selected because this component has its own state so there will be independent of each other okay now we don't need to list groups here so I'm going to remove the second one [Music] so we're showing a list of cities here but what if we want to show a list of names or a list of colors we don't want to recreate a separate component for each type of list right so how can we make this component reusable this is where we use props or properties props are the inputs to our components so back to our code instead of defining these items here we should be able to pass them as an input to this component just like how we can call a function and give it an argument now the same principle applies to this heading instead of hard coding this label here it would be nicer if you could pass different labels like cities names colors and so on so how can we do that well first we need to decide the shape of the input to this component so we should be able to pass an object with two properties items which is going to be an array and heading which is going to be a string to do that we use one of the typescript features called an interface using an interface we can Define the shape or the interface of an object so you start with the interface keyword give this a name by conventional use props but some people prefer to prefix it with the name of the component so list group props either way it works I prefer a shorter name that he Embraces would define various properties and their types so we want to have items which is going to be an array of strings so string array and heading which is going to be a string so once again we're using type annotation to specify the type of various properties okay now we don't need this comment anymore next we give this function a parameter called props of type props now if we go back to our app component we have two compilation errors saying type is missing the following properties from type props items and heading so the typescript compiler is saying that this component expects two properties which are items and heading we have not specified them this is yet another benefit of using typescript so the typescript compiler is reminding us that we have forgotten to pass these props so it's helping us to catch a bunch of potential errors at compile time before running our application so back to our list group I'm going to grab the list of items and move it to the app component now we can pass this just like how we said the attributes of HTML element so we set items to we add braces so we can reference this variable now similarly we should also set the heading to series now in this case I'm using quotation marks but we could also wrap this in braces but this is unnecessary because we're passing a static value so let's rewrite it that's better now the compilation error is gone so back to our list group component now there are a couple of issues here we don't have the items variable anymore so we have to prefix it with props dot okay but we have to do the same thing here this looks a little bit repetitive and ugly a better solution is to destructure this parameter right here so we remove the name and add braces and pick the two properties items and heading now we have access to these properties anywhere in this function so we can remove props Dot and our code is cleaner now the final part is to replace the list with The Heading dynamically okay back to the browser our app still working so using props we can pass data to our components foreign our list group component is in a fairly good shape when we click an item it gets selected but in a real world application quite often something should happen after an item is selected perhaps we want to filter a list of objects or maybe we want to redirect the user to a different page so something should happen after an item is selected now what happens is different from one application to another there is no one-size-fits all so we don't want to implement that piece of logic inside our list group component because then it's not going to be a reusable component anymore so we need a mechanism to notify the consumer or the parent of this component that an item is selected in this case the consumer or the parent of this component is our app component this is where we are using the list group so when an item is selected we should notify the app component that an item is selected but how can we implement this well that's very easy so look at our props object currently we have two properties and we are using these to pass data to our list group component now we can add a third property which is going to be a function now down here when we select an item we're going to call that function with this our app component will be notified let me show you how this works it's really simple so first let's define the signature of that function let's imagine that we want a function that takes a parameter called item of type string that is the selected item and returns void so it doesn't return a value so here we have a property by convention we start with the word on and then we specify the type of event in this case select item this is just like the on click prop that you saw earlier but here we have on select item so we have a property called unselect item the type of this property is a function that has a parameter of type string and returns void okay with that now we have a compilation error in our app component how can I tell look it turned red also we can go to the top under View open up the problems panel so the typescript compiler is telling us that in the app component we have forgotten to pass this prop so once again the typescript compiler is helping us catch a lot of potential problems early on so let's go back to our app component now here we set on select item we can write an inline function here just like how we handled the click event earlier or we can write a separate event handler if you want to write a separate event handler again just like before by convention we start with the word handle and then we specify the type of event select item now we set this to a function with a signature that we just defined so item of type string goes to nothing now here we can just do a console.log and print the item on the console now we can pass that down here handle select item now the last step back to our list group over here when destructuring the props we should pick the on select item property and then When selecting an item we should call this function so we call this and pass the selected item which is this item variable here now back to the browser when we select an item the app component is notified and it's now printing the name of the selected City on the console [Music] now let's talk about the differences and similarities between props and state as you have seen props or properties are the inputs or arguments passed to a component State on the other hand is the internal data managed by a component that can change over time so Props are like functional arguments and state is like local variables inside a function now one thing you need to know about props is that we should treat them as immutable what does this mean in English to mute it something means to change it so mutable means changeable and immutable means unchangeable so when we say something is immutable it means it's read only so in our list group component here are our props we should not change any of them here we should not set the heading to a new value if we do so nothing is going to happen nobody is going to yell at us but this is an anti-pattern in react you will understand the philosophy behind this as we go through the course this is based on functional programming principles so we should treat props as immutable or unchangeable State on the other hand is mutable and that's the whole purpose of using State variables we want to tell react that this component has data that can change over time right so these were the differences between State and props but one thing they both have in common is that anytime they change react will re-render our component and update the Dom accordingly [Music] sometimes we want to pass children to a component just like how we are passing a list group to this div element here so in this lesson I'm going to show you how to create a component that can accept children so back to our components folder let's add a new file called alert.tsx now let me show you a shortcut instead of defining a function here and then exporting it we can use a shortcut so here in the extensions panel if you search for es7 plus you will find this extension it's called es7 plus react Redux and react native it's a very popular extension look at how many times it's been downloaded so once you install this you can type RAF CE now it's not coming up I don't know why so let's close this file and open it one more time now let's try again good so this is short for react Arrow function component export so if you press enter we get this code snippet lovely now here we have multi-cursor editing so we can change the name of the component if you made a mistake but in this case no so let's go back to alert and then we press escape to exit multi-cursor editing good now we don't need to import react on the top so here's our alert component now let's add this to our app component and test our application up to this point so we go to the app component that we're done with our list group for now so let's delete all the code here now inside this div we want to add an alert so let's add alert good now back to the browser so here's our alert component lovely now to display an alert we're going to borrow some code from bootstrap so head over to bootstrap website go to the docs and here on the left side under components you should find alerts so let's find out the markup we need to render an alert like this so that is very straightforward we need a div with two classes the base class is alert that all of these have the second class is a class that determines the color so if you use alert primary we get this Blue Alert by default so back to our alert component let's give this div a couple of classes alert and alert primary all right this is what we get lovely now we need to make this Dynamic so we want to pass the text as a prop to do that first we need to use an interface to define the shape of props so Props here we need a property called text of type string then we add a parameter here of type props in fact it's better to de-structure this and grab the text property and render it right here okay now back to our app component here we should set the text to something like hello world before going further Let's test our implementation okay it's working lovely now while this works this way of passing text to this component is kind of ugly what if the text is a bit too long what if you want to pass HTML content passing HTML content has a prop like this is kind of ugly wouldn't that be nicer if you could pass text as a child to this component let me show you how so we want to be able to use this component like this this is better so to do that we go back to our component now there is a special prop that all components support and it's called children so if you simply rename text to children now we can pass our text as a child to this component but we have a couple of Errors because we need to rename these two references to text so I'm going to rename them both in one go good there is our con and our application is still working lovely now what if you want to pass HTML content here we get a compilation error because we told the typescript compiler that the children prop is a string but in this case we are not passing a string we are passing a more complex structure to solve this problem we need to change the type of children from string to react node now here in order completion box we have two react nodes the first one is an abbreviation so if you press enter here we get this markup this is not what we want we want the second item this is the react node class defined in the react module so let's import it on the top like this and with that we can pass HTML content to our alert component so to recap using the children prop we can pass children to a component [Music] all right the last thing we're going to cover in this section is react Dev tools which is a very useful browser extension for inspecting and analyzing our react applications it's available for Chrome Firefox and Microsoft Edge so simply Google reactive upper tools or reactive tools and install it in your browser once you do that then go back to this page here in the dev tools you will see a couple of new tabs one is components the other is profiler now look at the components tab here we can see the hierarchy of our components so on the top we have the app component and below that we have the alert component so this is the component tree that react takes and renders in the actual Dom now down here you can see the props of this component so here we have the children prop which is set to an array of two objects the first element is a string the second element is a span object below that you can see how this component was rendered so it was rendered by the app component now finally down here you can see where this component is implemented in this case in app.tsx but that is not visible in my recording window now in a large application with a lot of components finding the right component might be a little bit tedious so we can always search for them here also here we have a couple more useful features for example we can select a component and inspect the matching Dom element so if you click this and then go to the elements tab we can see the matching Dom element that represents this component now back to the components tab there's also another useful feature here so we can select the component and click on this icon to see its source code so in this case this is our alert component so it's pretty straightforward it doesn't really need more explanation as you're building applications if you want to better understand your components and how they work if you want to inspect their props and state use reactive tools [Music] all right now it's your turn I want you to create a bootstrap button component so here on bootstrap website if you look at the buttons page you can see we have different types of buttons now for this exercise I want you to only focus on this set of buttons because here we have other flavors don't worry about them don't worry about the sizes or outline buttons just simple bootstrap buttons now the markup is really simple each button has two classes one is BTN which is a base class and the other is a class that identifies the color so by default primary buttons are blue secondary buttons are gray and so on so I want you to encapsulate this markup inside a reusable react component so span a few minutes on this then be sure to come back and see my solution as I'll be showing you a really cool typescript technique all right here in the components folder we add a new file called button.tsx now we use our shortcut rough C good next we rename div to button and give it a couple of classes now I'm typing a little bit too fast because I'm assuming you have already done your exercise so I'm not expecting you to code along with me okay so here we have two classes for now let's just stick to primary buttons and then we make this Dynamic so this is the approach I want you to take while building applications one step at a time don't try to do too many things together okay so for now I just want to render a basic button I don't even want to make the text Dynamic let's see if our application works up to this point so we go to our app component and in this div we add a button component okay now back to the browser here's our button beautiful so the first step is done now the next step is to make the text or label Dynamic so back to our button component here we need to use an interface to define the shape of props now I want to use the children prop here so we can pass the text just like HTML buttons so I'm going to set the type of children to string we could also use react node but I prefer to use a string in this case next we add the props parameter and de-structure it and finally we render children right here good now we go back to our app component and give this button a label like my button let's see if our application is working good again don't worry about these errors everything is good so far next we need to handle the click event because in a real run application when this button is clicked we have to do something what happens next should not be implemented in our button component otherwise it's not going to be reusable okay so back to the button component here in the props object we need to add a new prop called on click and this is going to be a function with no parameters that returns void next we added here on click and finally we set the on click prop of the HTML button to the function that is passed from the outside so on click is going to be a function that is passed from the outside so the parent of this component is going to pass that function we get that function and simply pass it to this HTML button okay now in our app component we have an arrow because we haven't set the unclick prop for now I just want to add a simple inline function and log clicked on the console let's see if our application is working so click click click beautiful now the final step is implementing the color so we want to be able to pass the color of this button from the outside like this so we can set it to primary or secondary or whatever so let's add a new prop called color of type string I prefer to sort these props in alphabetical order it makes our code a little bit easier to read That's nicer next we add the color prop here and we use that to add the second CSS class dynamically so we wrap the codes in braces we terminate our string here and then append the color right after okay we have a compilation error because this quotation mark is unnecessary good now in our app component we have set the color to secondary let's see if it's working good if we change it to primary it's still working great now what if you want to give this a default value so we don't have to specify the color every single time to do that we go to our button class and give this color prop that default value of primary with that we get this blue button beautiful however we have a compilation error in the app component saying property color is missing in type so even though we gave this prop a default value the typescript compiler still expects us to set the color prop when using the button component to solve this problem we have to tell the typescript compiler that this property is optional so we add a question mark after and now the area is gone okay now what if we pass an invalid color here like let's say react what happens well there are no errors or Warnings but this is not how a button supposed to look like this is where we can use typescript to catch this kind of bugs early on before we deploy our application let me show you how so back to our button component instead of setting the type of color to string we can set it to a string literal like primary and with this we can only set this property to the value of primary so if you set it to something else we get a compilation error now we don't want to be limited to primary we want to support other colors so here we can use the union operator and add a second string literal so we can add secondary we can also add danger success and other bootstrap colors with this implementation we can only set this property to one of these values and nothing else so if we set it to react for example the typescript compiler is yelling at us we can see this file turned red and also if we go to the view menu and look at the problems panel we can see that we have a problem in this file so now if we change this back to primary or secondary or one of the supported values the arrow goes away [Music] all right here's the next exercise I want you to write the necessary code so when we click this button we see an alert and here we have a close button when we click it the alert disappears this is a great exercise for you to practice pretty much everything you have learned in this section now let me give you a hint on bootstrap website look at the alerts component on the right side you will find a link called dismissing now down here you can see that to make an alert dismissable you need to add a class here called alert dismissable you should also add a button this is the close button with this class and other stuff so spend a few minutes on this then come back see my solution all right this is so much fun so here in the app component right above our button we're going to add an alert and here let's say my alert now before going any further I just want to test our implementation up to this point I don't want to show or hide anything I just want to make sure if we can see an alert beautiful now we don't want to show this at all times we want to show this only when this button is clicked to do that we need a state variable here in the app component that determines the visibility of the alert so we want to render this part only if that variable is true so here we need to use the state hook to declare a state variable we initialize it to false so our alert is initially hidden now this returns an array that we can de-structure into two elements we can call the first one alert visible and the second one set alert visibility you could call them anything whatever you prefer now we want to render the alert only if alert is visible alert visible is true sober wrap is Embraces and perform a logical and between alert visible and this expression so alert visible and okay now when we click the button instead of logging something on the console we simply call set alert visibility to true so set alert visibility to true let's see if our implementation is working all right now we click and here's our alert beautiful let me explain how this works so when we click on this button this function is called at this point we set our state variable to true so the state of this component is changed and react will re-render this component and all its children this is why we see the alert now we need to add the close button to the alert so here on bootstrap website I'm going to copy some code I'm going to grab this class so there are no typos let's add that to our alert component okay we also need a close button I'm going to copy that from this website as well paste it here we just need to rename class to class name good now once again before we implement the hiding logic first we want to test our application and make sure that we can see the close button so one more time click okay here's a close button now the final part when we click this button we should notify the app component that the user clicked on this button at that point the app component will set the visibility of the alert to false which will cause the app component and all its children to re-render so to notify the parent or the consumer of this component that the user has clicked on the close button here we need to add a new prop on lows so remember the convention we start with the word on and then we specify the event in this case close this is going to be a function with no parameters that returns void now we need to add that here and finally when the user clicks on this button so unclick we simply call on close and more accurately we are not calling this function we're not calling it like this we're just setting on click to unclose so on close will be a function that is passed from the outside from the parent we pass that function to this prop when the user clicks on the close button react will call that function for us okay now we have a completion error in the app component because we haven't set the unclose prop pass and error function and set alert visibility to false as simple as that okay now the final test click click lovely congratulations you made it to the end of this tutorial I hope you found it helpful and learned a lot about react but wait there is more this tutorial was just a small part of my complete react course the full course includes eight hours of content and is jam-packed with the latest tools and best practices you'll get access to exercises summary notes cheat sheets and a project I showed you at the beginning of this tutorial and if you're not completely satisfied no problem the course comes with a 30-day money-back guarantee so there is no risk in giving it a try so if you are serious about master react I encourage you to check out the full course using the link below this video thanks for watching and happy coding [Music]
Info
Channel: Programming with Mosh
Views: 1,676,811
Rating: undefined out of 5
Keywords: react js, react tutorial, learn react, react course, reactjs tutorial, react crash course, react js tutorial, reactjs course, react tutorial for beginners, react.js, reactjs tutorial for beginners, reactJS, react, learn reactjs, tutorial, javascript, crash course, programming with mosh, code with mosh, web development, mosh hamedani, learn react js, typescript
Id: SqcY0GlETPk
Channel Id: undefined
Length: 80min 4sec (4804 seconds)
Published: Sun Mar 12 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.