React Router Crash Course 2Hrs!!!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on guys so in this video I'm going to go over the basics of react router now if you don't know what react router is it's a tool that allows us to make our react app operate more like a traditional website or a multi-page app word and so I'm going to start off by going over the basic concepts of URLs and I talked about what's the difference between a reactive versus a typical website we can then move on to playing around with react routes and I'll make sure to provide plenty of examples so that you guys can really learn how they work and I'll even show you guys how to make a protected route and then lastly we'll wrap up by taking a look at how the history API works in a normal website versus a react app and so I think I got you know roughly about two hours of content so hopefully you guys enjoy this video if you have any questions or if you want me to cover any other topics just let me know and I'll be happy to do so in this section we're going to start talking about react router and this is probably gonna be one of my favorite sections because once we add react router into our repertoire of tools you'll find that our applications moving forward that we build in this course are gonna be exponentially more complex and significantly more interesting but there are a few things that we have to cover before we can actually start working with react router and we have to really start understanding what URLs are we have to take a look at what happens on the back end when we actually click different links within a website and navigate to different URLs within a domain so I built out this simple diagram to help you guys understand what are the different components that make up a URL and so the first thing that you're going to see is the protocol so HTTP is the protocol here there's two main protocols we have HTTP and HTTPS the only difference between the two being HTTPS is secure and HTTP isn't and you'll see that most websites if you go to them they probably only run HTTPS so if you try to go to a website that says using HTTP usually it'll just redirect you to HTTPS then after the protocol we have the domain and this is the domain or the IP and here I just wrote localhost because that's usually what we see when we're testing our react application on our local development server but if you go to an actual web site like Amazon or Google you're usually going to a domain name right and so they actually have to purchase a domain name and so we use that domain name to basically route our HTTP requests to their server and so this can be a domain name you know like google.com or amazon.com or it can be an IP address because you can actually point directly to the IP addresses of their server but you'll find that you know because no one really remembers the IP addresses of the different web servers it's much easier to use domain names so usually what you guys are familiar with are going to be domain names then we have the after the domain name we have a colon and then we have the port number and when you visit web sites you usually won't see the port number because by default our web browsers will always use port 443 for HTTP in port 84 HTTP um but when we're working on our local development server you know we always use port 3,000 so I just wanted to point out where that is and why that is there all right and then finally from the slash moving forward we have the route and the route essentially will take us to different web pages within that website so let's go and take a look at a real world scenario right and so I've got this blog let me zoom in for you guys and it's called the walks of life the only reason I know about this was I was trying to learn how do you cook Chinese food the other day I tried to make a recipe from here and it came out like absolute garbage and I realized I could just spend $7 at China King buffet and eat my brains out so I was like you know what why am i chopping up onions like some loser but I do like to name the walks of life it's pretty clever right because you got a walk and then you get the walks of life that's a little play on words but here you can see that let's take a look at the URL so if you double click on the URL it's gonna give us the full URL so here we're using HTTP so this is going to be secure traffic and we got colon slash slash then we got the domain name which is the walks of life com so whoever runs this blog purchased this domain and this domain is gonna be associated with some IP address of their web server that's located who knows where and basically when we go to this domain name we're going to the /url right so if I type in slash and hit enter it takes me to the same page so what happens is this goes and sends a request to their server and the server when it sees a route of /url basically is going to respond back with an HTML page that's going to represent their home page ok but if we select the about link you'll see that the URL changes to slash about slash right and so the server when I sent a request to the slash about path or route it responded back with this HTML page which looks significantly different right and then if I hit recipes and then hit you know visual recipe index you can see that this is a different route and I get a completely separate page so this is what's referred to as a multi page app where the server that's hosting this website basically has a whole bunch of different HTML files and each HTML file is going to represent a different page on this website the way that the web server determines what to HTML file to send to us the user is based off of this route right so if we send visual recipe index it's going to be configured to send the HTML file associated with this link and you can see that if we go to how-to and hit all posts you can see that the route changes and now we have a slash category slash cooking methods and so there's a ton of different routes on this website and the reason I want to go over this is because react works a little bit differently react is what's referred to as a single page app so what happens is and I'm gonna cover this all in the next video I just wanted this to I just want to make this video so that you guys had a slight intro into URLs and routing but react always just sends the same index.html file and so we have to use a special package like react router to make it operate more like a traditional website or a traditional multi-page application alright so hopefully you guys have a better understanding of URLs and how routing works in the next video I'm going to explain how react router actually allows us to kind of transform a react application into a into a moral into a multi-page application while still maintaining single page application functionality hey guys in this video I've set up a few diagrams for us to take a look at so that we can better understand how a traditional website operates when it comes to navigating to different routes and how a web server will handle these different routes and then after that we'll then take a look at how react will handle this because it will be a little different but once you see how it works you'll see that it's pretty simple so in this diagram we've got a web browser so this is gonna be the user side and then we've got a web server on the right side and this web server is going to host the web application and so when the user navigates to the route of slash home what's gonna happen is we're gonna send a get request to the server and the server he's got a ton of HTML files right so he's gonna have one for the home page he's gonna have one for the about page and he's gonna have one for the contacts page as well as any other pages within the application and the server has a mapping of you know what route maps to what HTML files so when he sees a route of slash home he knows that he needs to send the home dot HTML file so then the server responds back with the response and he sends the home dot HTML file and then the user loads that onto the screen and then he sees all the contents of the home page now if the user navigates to the slash about route what's gonna happen is we're gonna send the request just like we did before the server will see that we got a route of slash about and he knows that he needs to send it to send the about dot HTML file back to the user so then the user receives the about that HTML file loads it onto the screen and then we see the contents of the about page and this is going to be the same for all the other pages the server just keeps the main idea behind a traditional website or a multi-page application is that there's a different HTML file for each route now in react this is going to be a little bit different and what I want to do is I want to show you guys the previous project that we were working on which I think was the expense tracker and I want to show you the public folder so this is the folder that we're going to be hosting on a web server and so we've only got one HTML file in our entire application we've got this index.html and if we scroll through the rest of the files you'll see that they're all javascript files are components and there's no other HTML file so when we host a react application the web server can only ever send this index.html file that's really how a react application works and then once the HTML file gets loaded the JavaScript can then take over and then load our content dynamically if we take a look at this diagram what's gonna happen is let's say we navigate to a specific route and we'll say we're going to the contact page right so we send a request to the server the server can only respond back with the index.html file so he sends that back but what happens is the react app sees that the route is for the slash contact page and so what he does is we have two he loads up the contact j/s component and this is a component that we have to define ourselves and this component is going to be like a wrapper component across all of the components that going to make up our contacts page so instead of actually loading a contacts HTML file we're instead of loading a contact Jes component which will then contain all of the code and the logic and all of the HTML for our contacts page and we load it dynamically now if we then decide to navigate to let's say the slash about we're out you're probably thinking well what do we do now we do we send a get request with the route of slash about to the server well we could do that but that wouldn't make sense because the server can only send back the index.html file because that's the only HTML file that he knows about and we already have that loaded in the web browser so there's no point in us sending a message all the way back to the server just to get the same file we already have so instead what happens is react router will intercept this request and he'll see that we want to navigate to the slash about route so what he'll do is he'll just basically take that information and he'll just tell react hey I want you to load the about j/s component and so this about Jas company is like the contact Jas component except it's gonna contain all the data that's associated with the about page and so that's gonna load all of that up dynamically and from the users perspective right he's not going to know that we didn't go all the way back to the server to retrieve this data because JavaScript is going to load up all this new content it's gonna look like we've navigated to a different page even though the web browser never refreshed the page because JavaScript did this all on the back end and loaded this all up for the user and that's why it's kind of referred and that's why it's referred to as a single page app because the user never refreshes the page the browser never refreshes the page we load different data with JavaScript depending on which route we navigate to so if we go to the slash contacts page we load a context ijs component and if we load if we navigate to the slash about page react router is just going to load up a different component that's going to show different data and that's it guys that's really react in a nutshell it's not complicated at all I'm gonna show you guys a simple application after this and you'll see just how easy it is to work with all right guys I think that's enough theory when it comes to react router so let's go ahead and get our hands dirty and let's start building out an application so I've created a new project using the create react tool and so you know we've got all the default code which I'm going to delete as usual in here we're gonna create our index KS file and we're going to import the usuals and we'll also need to make our fjs file you before we start our application we need to do one thing in that import or install react router Dom go ahead doing an NPM install react router Dom and you need to make sure you add the - Dom I guarantee you someone's gonna forget this you don't want react router you won't react router Dom all right and let's do an NPM start we save all as well yep so we've got our applique and when I want to build out is just a a basic site with some common pages so we're gonna build a home page we're gonna build an about page we're gonna build a contact page we may even add like a blog page or something so you know traditional links that you'll see on most web sites so let's go ahead and do that I'm gonna make a new folder would've call this components and then within the components let's add our pages so we're gonna make a home JSX just return something arbitrary like home actually what I'll do is I'm gonna put in an h1 tag we'll say home just type in lorem 100 and that's gonna get some whoops lorem 100 and that's gonna just generate some random text just to fill out our screen and then we'll add in about JSX you and we'll make a contact JSX you and then finally let's make a blog page you all right so we've got all of our pages let's say that I to change our application because we actually haven't wired it up to handle the routing so let's go to our application now and here what we want to do is first of all let's import all of these pages because we're going to be using all of those so we'll do import about from /blog are about you Blagh from you okay so we've got all of our pages imported the last thing we need to do is import browser router from react router Dom I'm gonna do that at the top we'll do import I'm router and we'll actually need a few other things so to route and we'll eventually get to switch as well so add those three and then we'll do from react router Dom and I'm gonna delete this for now and then we'll just do a multi-line JSX expression and what we want to do is we want to wrap our application within with the browser router tag so this is going to allow us to route between different pages you and to actually set up route but we have to do is we have to define a route tag and then we have to specify the path so if the user goes to the slash route we want to send them to our home component right send this to /home and let's copy that and let's set up one for each and every link that we have so we're gonna have one for about going to go to our about component we're going to have one for contact gonna go to work on tech component and then lastly we're gonna have one for our blog and that should send them to our blog component we this makes sense it's pretty straightforward all we're doing is browser router when it receives you know a user going to our website it'll check the route within the URL so if it sees slash home all its gonna do is load up this component right so that's how we're handling making our application look like a multi-page application we're just loading up a different component and right now this home component basically represents all of the components that make up our home page but right now is just an h1 tag with a whole bunch of text but when you actually build out an application you know that's going to be it's going to be a lot more complex than this there's going to be multiple other components within our home page so I just keep that in mind all right and so let's save this and let's test this out okay so when i refresh the page you'll see that we see nothing on the screen and that makes sense because you'll see that we haven't set up any routes for the slash right for just plain slash we only have it for home about contacts on blog so if I type in slash home hit enter we can see that we load up our home component and if I do an inspect let's take a look at our components ignore a lot of these routes but you can see that right now we've got our home component loaded right if I change this to slash about you'll see that it loads up the about page and the only page that's are the only component that's getting loaded from the components that I've defined is the about page and let's wrap up by verifying our last two links that we got contact so our contact page works and then we've got our blog so our blog page should work as well great okay so everything's working now before we move further there's one strange behavior that I want to point out with how react router works and it's it's gonna seem like it's broken but it's not that it's broken it's actually giving us a little flexibility but it may be what we don't want so we have to add in a few us a few attributes to modify how it behaves so that we force it to behave in a way that we would think it behaves and to do that I'm going to change the our home page to slash because that makes sense right you know a lot of home pages are just located at the you know root directory so let's save that I can't go back to slash here as well and I saved that okay so now when we go to our slash we're gonna go to our home component that makes sense everything working just the way you expected it to what's gonna happen though is once we go to the about page we're gonna see some unusual behavior that's if I go to about enter you're gonna see what I'm talking about right for some reason we've loaded up our home component as well as our about page and if we inspect with the react dev tools you'll see that we've got and about getting loaded up and what's up with that guys right that's a little weird but if you take a look at how react router works it's going to make sense why it's doing that so what happens is react router doesn't look for an exact match on the URL so what happens is he goes down this our react routers gonna go down this list of routes and it's gonna see if it matches slash and the thing about this URL is technically we do have the slash right so that's why it's matching the homepage because it has the slash and so it matches that except it doesn't exit out of there right so it's going to find a match and then it's gonna keep going down the list to see if it finds any other matches so if we do a so if we go to slash about right we have we match this URL as well right because it's slash about so we load up the about component as well and it's going to be the same for all the other pages if I go to contact right react routers going to match the slash so he's gonna load up the home component and then he's gonna go down this list he won't match about but he will match slash contact and he'll load up the contact page as well and so this is probably an undesirable undesirable behavior however it does give us flexibility when it comes to how we load up different components based on the URLs but for just navigating between pages this is usually not what we want and so an easy way to get around that is on the main URL for the slash we add in the exact attribute and so what this is gonna saying is that this will only match when it's only just a slash so if it's slash contact this is not an exact match we'll go down the list to see if any other components match so if we hit save and so now when we go to the contacts page we just have the contact because even though there is a slash it's not an exact match because it's slash contact and let's verify our other links so if we go to about should be just the about page and then if we go just to slash it matches just as well and I do want to reiterate the fact that you know even once we get a match within our router we're gonna keep going down the list to see if we have any other matches and for that I can show you that with this contact page again and if I just copy that and paste that in again and then this time add a different component will add the about and then hit save and now if I go to contact right it loads up the contact and the about page because it matches this first this first route route and it's gonna load up the contact component and then it goes down and it sees what other routes and matches and then it matches this other contact so then the loads up the about as well and you may or may not want this behavior but if you don't want this behavior all we have to do is use the the switch method I think it's called a method but either way is easy all we do is we take all of our routes and we wrap it in a switch tag and we're gonna take our switch tag our closing tag and we're going to wrap it around the bottom of our routes and all the switch is gonna do is it's gonna say that the after we match the first route we're going to stop looking for other routes so we're only gonna load up one component always and so now if I hit save and we go to that slash contact you'll see that we load just eat whoops I looks like I deleted the other one let me add that back I don't know why I did that we want to make sure we add about page now so before remember we were loading up contact and about when we went to slash contact but hit save you'll see that we do not load up the about page because what happens is we go down this list we find our first match and then we see we match this statement right here we load up contact and because we're in a switch statement we're going to break out of this and we won't look for any of the routes that match it's always the first match that we load up and so if I move this up above the current one you'll see that we now load up the about page when we go to contact and that's because this route exists before this route so this is going to be the first match and react router is going to load this up and then break out anyway so we don't need that and let me go ahead and delete that I guess so that was just a brief intro to react router in the next video we're going to keep adding some functionality to this website because right now to switch between pages we have to manually go in change the link and update it but an actual website is either going to have links on the page that take us to different pages or at least a navbar that allows us to kind of navigate between two pages so we'll I will take a look at how we can implement that using react router in the next video in the last video we set up a few different routes for our application so we have one for the home page one for the about page one for the contact page and one for the blog page however the only way to navigate between them is to manually go in and change the URL and so what we're gonna do now in this video is we're going to build out a navbar with links that we can click to take us from one page to another so let's go to the components folder we'll make a new component and call this navbar and I'm just going to do our a FCE and for now let's just get this loaded so I'll do navbar and what we want to do is we want to import it into our app file go to import navbar you and let's see where we want to put this I you know we could technically put it up here but you're gonna see that this will this won't work once we get to a later video it'll break it when we started using link tags so what we want to do is for the navbar we want to put it within the browser router however we don't want to put it within the switch statement because if we add a route in the switch statement what's going to happen is we're only going to load the navbar for one of our pages and we want the navbar to load up on every single one of our pages regardless if it's the home page or the about page of the contact page and so to make sure that the navbar is loaded on every page we'll just put it right here above the switch statement but within the browser router tags so let's do navbar all right and let's do a save all and we've got the navbar and if I go to another page contact we should see that the navbar is still loaded so that means everything's working we've got our navbar being rendered out on every single page now let's go add a few links into our navbar so that we can navigate to different pages within our application I'm going to change this to a multi-line JSX expression and we'll do a ul for some links and then we'll do an ally for each of the different links and so you're probably thinking you know how do we set up links so you're probably thinking that you know for links within our application we just use an anchor tag right because that's what we normally do so let's try that out so we'll do a and then the href so for this one's gonna be for home so I'll say when we go to slash home or we go to home when we click this link and this will say link this will say home and then for about this will be about and about contact and lastly we need one for block all right so we've got our links in place let's save that and let's see how this all works out okay we've got our links and let's try this out so right now I'm on the contact page let's see what I happens when I hit home okay it looks like it's kind of working if I hit about takes us to our about page if I hit contacts it takes us to our contacts page and if I hit blog it takes us to our blog page so it looks like it's working however behind the scenes were actually breaking a few things okay and what I want you guys to do is focus on the network tab within your chrome developer tools and notice what happens when I click a different link so this is going to show us any you know like network related requests and so you know here we went to slash blog and it's saying that we sent a request let's see headers we sent a request to HTTP localhost colon 3003 slash blog so that means we're sending a get request all the way back to our web server which is just our development server in this case but we're sending it back to the web server and the web server is responding with our index.html so this response is our index.html which is within our public folder that's this file right here and so you'll see word for where it's the exact same thing and you're gonna see why this is bad okay so if I hit contact right another Network request but this time we sent it to a HTTP colon slash last localhost colon three thousand three slash contact so once again when I clicked a different link we went back to that web server and we asked for a get request oh I'm sorry we asked for we sent a get request to them and they responded back with the index.html right which is a waste because we already have this index.html and we never want to send a request back to the web server when we're working in a react application or any single page application and keep in mind that every time we do this we're actually refreshing our page right and you'll notice the little refresh if I hit a blog you'll see that it refreshes right and that means anytime we refresh we're losing all of our state in our applications so all of that state - all that information about the application is going to get deleted when we click on one of these links and that's because that's the default behavior of an anchor tag an anchor tag is always going to refresh the page and send the request back out to the server and retrieve a new HTML file and so to prevent this behavior what we have to do is instead of using anchor tags in our react application we have to use link tags and these special link tags are from the react router Dom library so we'll import that you you and I'm going to change this to link you okay so I've changed them all to links we need to remove the href because there is no href attribute within a link tag instead it's called too but it does the same thing so anytime someone navigates to slash contact we're going to send them to the contact page and we're going to remove this and change that to a two and this is going to be about you okay so let's save this and let's go to our our elements tab and let's see what happens or what gets rendered out when we actually use a link tag if I go to the body then our route we've got our you l's and then we've got our links okay and so you'll notice that this link tag just renders out an anchor tag so it's basically exactly what we had before when it comes to how the HTML gets rendered out it does nothing different it just renders out an anchor tag for us however the main difference is when we use a link tag it prevents the default action of when an anchor tag is clicked so when these anchor tags get selected will no longer perform the default behavior of sending a request back to the web server right it's kind of like you know when we submit a form and react we always have to do that event that prevent default this is essentially doing that for us I and so instead of having to send a request back out to the server instead we let react router Daum take over and load up the correct component based off of the URL that we're navigating to and so I'm gonna go back to the network's page and you'll see that since we're in the blog page we sent a request to local host / blog and that makes sense because that's the first time we've loaded up our application however if I hit home you'll see that this didn't refresh right it still says blog we didn't send another net rip network request but we've loaded up the home component and if I select about we navigate to the about page but we don't send a new request and we go to contact that works as well and all of our state is still intact even though we don't have any state in this application at the moment but this is the purpose behind using link tags is that they're going to allow react router dumb to just load up different components instead of actually performing the default behavior of an anchor tag okay so I think that covers links for this video in the next video I'm going to perform just a tiny bit of styling I know I don't really like to focus too much on style in our quote in this course but you'll see why I want to add a little style because we're gonna cover nav links which is similar to links but it's slightly different but I want to add some style to actually show you how that can be used properly so we're gonna do a little bit of styling for application so we're gonna make our navbar look a little better so let's go to our source folder and let's make a new file so this is gonna be our CSS file and all I'm gonna do is I'm gonna copy some the CSS that I've already written beforehand and I'm just gonna paste it into here and I'm just gonna slowly just kind of scroll down so that you guys have a chance to copy all of this onto your onto your project code and I've also include this in all other project related files in the course so if you go to the last video of this specific project you'll see that we have the completed code in there and so you can just copy that and paste it into here so now that we get our CSS we need to import our CSS so I'll do import you app that CSS it save and it looks like it did nothing so let's make sure we didn't mess up something ah that's right so now we actually have to go into our navbar and change up the JSX that we're rendering and so the first thing I want to do is let's just comment this out for now we're gonna add some nav tags and then within there we want to add a a link I'm going to add a link tag that's gonna say it's gonna have a class name of logo and that's gonna go to slash like we had before and this is just going to say brand logo so this is gonna be like the logo of our website and so this is going to be like our button to get back to our homepage then we want to div with a class of Naf - links and then here we want to add another link and this is going to have a class of link Oh Duke last name equals link and it's going to have a to is going to be for the about page about and we can just copy this a few times so then we've got the next one which is going to be for contact and then finally blog alright let's save that and let's take a look alright so we've got our CSS in place and that's all I wanted to do in this video so this is gonna be just a short video you'll see in the next video why I actually ended up styling this you're gonna see that we're going to introduce something called nav links which operate pretty similar to links but there's gonna be one slight difference I and I needed to make sure that our app was styled properly so that I can show you the difference all right now that we've got our app styled I want us to import nav link from react router Daum and nav links operate pretty much exactly the same way that links do but there's just one minor difference and I'm gonna show you that real quick so let's um let's change all of our link tags to nav likes and an easy way to do that with vs code is if you click on one of the links and just hit control and then D and then hit it again it's gonna find all the other instances of links and then we can just type in nav link and it's going to update all of them okay so let's it save and now if we go to our elements and let's go to our div and then we go to our nav and then let's go to our links and I want to show you something very specific and that's right now we're on the contacts page and if you take a look at the classes that are assigned to the contacts page you'll see that we've got an active class however if you go to our CSS file I don't have sorry if you go back to our navbar you'll see that no where am i placing the active class on any of these linked tags and so this is actually a react router doing this so what it does is when you change this to nav likes it's gonna find which route you're specifically on and it's gonna automatically add a class of active for you so if I hit blog now right you'll see what changes contact no longer has a class of active but blog now has a class of active and if I do if I go to about you're gonna see the same thing we've got one we've got an active class on about and it's been removed for the other two links so this so that's the only difference between links and nav links is that nav links will automatically find out which page that we're on and it's going to automatically assign a class of active and why would we want to have a class of active well you know usually in a navbar you're gonna kind of highlight the fact that you're on that page right in some way shape or form usually either changing the color or adding like a background or something so if we go to our app dot CSS and we can just do state sorry we can do class of active and I'm going to just change the color just a little bit so I'm just going to copy this right here sit in here and I'm just gonna change this to like 0.9 so it's gonna make it just a little bit darker and so now you can see that the about page is a little bit darker if I hit contacts you can see now contact is a little bit darker and that's because now contact has that active class which then sets the text color to this color and then if I select blog you can see that it gets a little bit darker than the other two so this just provides a little bit of feedback to the user to let them know what page they're on now you may want to adjust what class react router assigns to the active link and we can do that by going back to navbar and then assigning a attribute called active class name and then we can set that equal to anything that we want so let's say we wanted to change the active class to with a selected page and gonna copy this and just paste this on all of the nav links save and we go to our developer console and then go to the nav links you'll see that for the selected page which is right now slash blog right because we're on slash blog we now add the class of selected page and so we can go back to our app dot CSS and change this to selected page so we can get the same behavior with the slight darkening all right so now blog is a little bit darker I select contact now that's a little bit darker i select about that's a little bit darker and you can see that we've assigned the selected page class to that link and so that pretty much wraps up how nav links work alright guys so now what I want to do is I want to take a look at our blog page and I want to make a slight modification let's say for our application or our website instead of just having a static blog page I want to break it out into categories so let's have a category 4 or say like dogs let's have another category 4 you know blog about cars maybe one for recipes and so we can accomplish this using relative URLs and paths and I'm going to show you guys how to do that in this video so what we'll do is let's go to our blog component and I'm gonna just delete this h1 tag we don't need that anymore or any of that text and what I want to do is go to their components and add a dog CAS X so this component gonna represent all of our it's gonna represent our dog blog and then we're gonna have one for cars and then one for recipes whoops just delete that should be recipe JSX you I'm just gonna put in recipes and then dogs we're just going to do the same thing and then we'll do the same thing for cars as well you all right and so when we navigate to the blog page what I want to do is I want to have a few links that will basically take us to either the cars page or the dogs page or the recipes page so like we did before let's uh set up our links I'm just going to set up a ul and then a few allies and then within the Li that's going to be a link tag so let's import link from react router Dom so I'll just do link and then this should import it there we go and then we need to specify the path so how I want to set up the routing within our website is anytime they want to go to the dog blog or the cars blog or the recipes blog the user needs to navigate to slash blog and then from there they'll do either cars or dog or recipes okay so what we need to do is we need to get the URL of the specific route so what we need to do is we need to get the relative URL so what we'll do is I'm going to delete this for now and we're going to use a special hook called use route match we're going to import that from react router Dom and I'm going to set this to you I'm gonna D structure both paths in URL because we're gonna use both of these and let's just consult out log both of those so if we do console dot log path and then URL let's take a look at what that looks like we'll put this within our yeah this is in our blog so if I hit save and we go to blog slash recipes we take a look at this we can see that we went to blog blog okay so that's going to be the relative URL so we're within the blog and so what we want to do is for the link we want to set the to attribute to we're gonna do a template string here and we'll say that we're gonna put in the URL that we have so this is going to go up to blog so we'll get all of this localhost up to blog and then from there we want to go to recipe so that'll be the first link and I'm going to copy this and paste it a few times and change it so then the next one is going to be dogs and the last one is going to be cars all right so hopefully this made sense we're getting the relative URL so right now when we get to the blog page we know that it's going to be a slash blog and then from there we want to send a link that goes to blog and remember URL is just blog so we go to blog slash recipes or blog slash dogs or blog slash cars then let's go ahead and set up our routes so I'm going to put in a switch statement because I only want to match one and I'll set the first route we're gonna have to import that as well so we'll import Prout so we just imported it in there and we'll send the path is equal to you and here we're gonna do pretty much the same thing as we did here so we will do curly braces and then we'll do a template string and then we'll match path so this is gonna match the path and this is also going to come out to being blog as well so technically we could put in URL but you want to stick to path for now and so we do path and then slash and then we'll do recipes so this route is going to take us to recipes and we want to load the recipes component and we'll copy this and we're going to paste that a few times and so we'll just change this to dogs and cars you let's hit save and it looks like we got a few errors but let's see what that's about and let's just do a save all okay so now put in text into our link so let's add that in there so do recipes dogs you and then part and let's go back to the homepage first okay and let's see how the navigation works so I'm gonna go back to apt at JSX and so when I hit blog we're going to it's gonna take us to slash blog that's gonna be our route so we'll load up the blog component right then we go into our blog component and we render out a few links and so first we're gonna get D structure of the path and the URL and that's going to be slash blog right and then what we do is we set up relative links so relative to where we are right now which is what URL represents we're gonna set up a link that goes to slash recipes and then another link that goes to slash dogs and then another one that goes to slash cars so it's always gonna be blog recipes blog dogs and blog cars and then we set up a few more routes from the blog page and these are all going to be relative routes as well and it's gonna be relative based off of the path that we currently are at right now which is slash blog and we're gonna get that from the path variable and so we're gonna set up a route to slash blog a slash recipes a route to slash path sorry / blog slash dogs and then slash blog slash cards and so if we go to slash if we go to slash blog slash recipes it's gonna load up the recipe component and this could be the same thing for dogs and then it'll be the same thing for cars so if I select recipes you can see we loaded up the recipe component please like dogs and load up the dogs and we load the cars what happened to cars did I not save this I put a D right here alright so now I do cars there we go so all three of her sites or sub sites I'll work in so that's how you kind of set up nested routing where we can set up relative routes based off of what page are on and we can always go to one of these pages directly so let's say we're on the home page and I want to navigate to that cars block well I can do blog and I can do cars and that's gonna take us directly there all right so in this video we're going to setup a simple authentication system and this isn't going to be a real authentication system because that's really outside of the scope of this course instead all we're gonna do is we're gonna use the context API to provide a simple boolean as a state and that bullying is gonna be called is logged in and that's basically gonna signify whether the user is logged in or logged out and the reason we're doing this is because in the next video I want to show you guys how to set up protected routes using react router and to do that we need to have some sort of authentication or some kind of way to determine if the users logged in so we're just going to have a simple boolean that's going to keep the state of whether the user is logged in and we're going to provide that using the Kitab the context API so that all of our components have access to it alright so let's go ahead and get started on making that I'm gonna go into the source folder we'll make a new folder called context and then within the context I'm going to make a new file and we'll call this off context Jas I'm going to import react and then we're going to create our context our context Alisa export Const and we'll call it off context and then we'll need to import create context and then let's define our provider component you and here I'm going to define our state so it's going to be called is logged in and this is just going to be a boolean and by default it's going to start off as being false which means the user won't be logged in and let's make sure that I import you state so we'll let Visual Studio code do that for us and then I'm going to set that back to false you and here I'm just going to pass down both of those so is logged in and it's well as a set is logged in just because I don't feel like defining like a handle function and then passing it down we can just pass this down and update it within the other components close and we want to make sure that we render the props children our context setup now let's go to our navbar and within our navbar I want to add a button and this is going to be just a simple button and basically what we're gonna do is based off of whether the user is logged in actually let me wire up the context first or our provider so let's go to our app component and let's wired it up here so we'll do auth context provider and then we're going to wrap our entire application with that you and now let's go back to navbar and let's actually import the context so we'll do Const and then we're gonna make sure we do structure out is logged in and set is logged in and then we need to import use context and we also need to import context all right so we've got our consumer set up now and set up the logic for a button so what I want the button to do is when the user is logged in I wanted to say logout and when the user is logged out I wanted to say login and then basically we'll set up an on-click event handler so that when the button is clicked we're going to change this state of is logged in so that's how we're going to kind of represent how we're logging in and out of the application so obviously not real authentication but it's going to do just enough so that I can show you guys how to set up protected routes and react and so here all we have to do is just pass in some curly braces and we'll pass in some JavaScript so we'll do is logged in so if the user is logged in what we want to do is we want to say log out and if he is not logged in we want to say login save and we see it says login because the default state is that the user is logged out then we need to handle the logic for when the button is clicked so if I do on click equals and then here that's an arrow function and we'll say set is logged in you make this little bigger a capital s too many letters you and we'll just say we're gonna set it to the opposite of is logged in so that's going to toggle our authentication status so let's hit save try this out so right now if we go to our components and let's go to our context provider and so right now we see that is logged in and set to false so if I hit login you can see that it changes out to logout now and it says that is logged in is true and if I click that again it says login and we've changed it to false all right so we've we've set up our authentication system so in the next video we'll go ahead and set up some protected routes and I'll show you guys how reactor router handles that now that we have our authentication in place let's go ahead and set up a protected route so the first thing is we're gonna create a new component I'll just call this some admin so like this can represent the admin page of our application so this is something that you would want the user to be logged into before they can access this page so I'm gonna go into components we'll do new file and I'll call this admin JSX and I'll set up the boilerplate for that and we'll just render out an h1 tag that says a headman fit so this is going to be our protected page right here the next thing that I want to do is we have to go into our navbar and set up a link so that users can access this page so I'm going to copy this right here and just paste it step below and just make sure we change the two to admin and this is going to say admin set up the routes in our app KS so I'll copy this you and I'm going to change this to admin and so right now if I do a save all we should see the admin page or the admin link pop up and so now if we click it it looks like it's not rendering that page let's make sure that everything is working so let's see slash admin that's good oh right here I forgot to change this to admin and we're gonna have to import it as well so I'll automatically import that and now if I select this let me go back to the home page so if I select the admin page you can see it takes us to the admin page so right now it's not a protected route and any user can access it so to make this a protected route there's a couple of different ways of doing this I'm gonna start off by showing you the simplest method of doing this in this video and then in the next video I'll show you another way of doing it which is a little more complex but it's just another way of doing it so let's go to our admin JSX and what I'm gonna do is I'm going to import our is logged in State so I'll do const the structure out is logged in and then we'll say that's equal to you'd use context so I'll import that and then I'll import in our off context as well and all I'm gonna do is this very simple if statement so I'm gonna say if the user is not logged in so if not is logged in I want to perform a certain task and within now what we can do here is we can actually redirect the user in this if statement so we're saying that if the users not logged in I want to redirect you to let's say the home page or you know usually in an actual website you would redirect them to a login page but I don't technically have a login page so I'm just gonna redirect the user to the home page and to do that we actually have to import one thing from react router dump so we'll do import and we have to import the redirect that's going to be from react router Dom and all we have to do is just say returned so we need to return the function and then say redirect equals and then we want to set whatever URL that we want to redirect to so we're gonna send them to our home page which is just slash and we'll close out that tag and let's give that a shot okay so let's go to our home page so right now we're in our home page and let's see what happens when we go to the end page and keep in mind that since it says login here that means we are actively not logged in so we are logged out at the moment so if I hit admin you can see that nothing happens right and so it's basically just redirecting me to the home page really quickly and we can I can show you that so if I go to blog and then hit admin now it just takes us to the home page however if we hit login and now if we hit go to admin page it takes us to the admin page so we now set up a protected route we're only logged in users can view alright so um in the next video I'll show you guys how to create a special component or a special route component that'll perform this same logic okay guys in the last video I showed you guys how to make the admin page a protected route and it was pretty simple all we had to do is just set up an if statement to check if we're logged in and if we're not we just redirect to our home page huh so in this video I'm gonna show you guys a slightly different way of doing this I'm gonna comment this out for now and this should make this page no longer a protected page so if we go to if we see that we're not logged in at the moment if we go to admin you can see that we can access the admin page alright so this is now a public page just like the about page of the contact page and what I want to do now is I want to define a new component we're gonna call this private route JSX I'm just gonna do in our AFC so we'll create this component and this is going to be a special component because the whole purpose of this component is to behave just like any other route component from the react route or Dom library the only difference is that it's going to return a route component so it's going to be a route component that returns another route component and the reason we're doing this is because within this component we can add a little extra logic to say you know if the user is logged in we want to do something and if the user is not logged in and we want to do something else and so there's gonna be a few things we need to import so the first thing is we need to get access to our is logged in state so I'll do const is logged in equals use context and then we do off context all right so we've got our state now and what we want to do is we want to return a route a standard route component so we'll do route I'm going to have to import this from the reactor outer dom library so I'll just click that and then we have access to so first of all what I want to do is we're gonna have passing a lot of props into our private route component right and the props we're gonna pass into is if we go back to you app JSX we know we're gonna pass a child proper because that's ultimately gonna be the component that we want to render but there's gonna be a few other props like the path prop and a few others that are gonna get passed down so we need to essentially save those so we'll say I'm going to basically D structure all the props and I'm going to grab the children prop and store that in a variable called children and then I'm going to take all the other props and I'm going to store them in a variable called rest so this just means the rest of the props so we got children and then the rest of the props and what I want to do is I want to then pass the rest of the props that we gathered and pass it into this route component that makes sense right because any of the props that are getting passed into our private route that we're going to declare right here we want to pass it down into the new route that we're going to return so I'm going to just spread those out so we'll just do rest and then finally we're gonna call the render prop the render we can then pass in a function and here we'll pass an arrow function with props and then we'll say we're going to console Dell we're going to return and then basically I'm gonna do a ternary operate and say that if we are logged in I'm going to return children all right remember we D structured out the children prop which if we go back to how a route is to find the children prop is going to have the component that we want to render out so I'm gonna I'm gonna render that out or going to return that from our of route component and if we're not logged in well then we're going to just do a redirect and we're going to have to import that in as well so I just did that there and I'm going to redirect that to the home page and it looks like we've got some errors hold on let's see what I did wrong here and we need to close this off as well we go so what we're doing is we're just taking the normal prop props that come into the route component and then we're gonna return a new route component depending on if we're logged in or not okay so it's pretty straightforward if we hit save then we go down to app JSX and we're gonna change our route component here to will be a private route so we'll do private route and then we'll import that and then we got to change this to private route it Save and so now let's give this a shot so let's go to admin we got redirected to the home page so it looks like it's working let's login and let's go to the admin page and it works all right so now our custom component works perfectly and so now anytime we want to set up a private route instead of just nesting it within a route component we're going to nest it with a private route component now there's a one thing I want to point out and there is a slightly different way of defining routes so here I've been using the child prop however we can change this and actually define it in a slightly different way so instead of defining it with a child prop we can actually do route and then here you know I had the exact the exact attribute passed in and then we'll do path equals slash like we did before I'm but we can also specify component right and so here this is going to tell us what component we want to render so here I'll say we want to render the home component and then I'll close that out so self closing tag I hit save and then I hit go to our home page it looks like it's working so if we go to about it's working home page it's working so this is just another way of defining things and this is you know logically gonna do the same thing as defining our routes like this where we pass in a child prop so you know do whatever you prefer the only thing I wanted or the reason why I wanted to highlight this difference is that our private route component that we defined right here this is only gonna work when we pass in our child prop so only it only works when we set up routes like this now we can get this private route component to work when we have it set up like this and I'll show you that in a second so I'm going to define a new component and I'll just call this a private route to JSX just to show just to you know signify that it's different and for the most part the logic is gonna be exactly the same we're just going to modify just a few things so here we'll do Const and then actually let me just do our AFC for now and we know we're going to have to import our states or do Const is logged in do use context and then off context and here when we're destructuring out the data we no longer care about the child prop right because we're not passing in a child prop instead we compare we care about the component prop so let's de structure that and so we'll go back to private route to we'll D structure component however we're going to decide spelled that wrong component however we're going to D structure that out and rename it to a component with a capitalized C and the reason because the reason we're doing that is because we want to make sure that when we call component that this is actually capitalized because react expects all components to be capitalized so that's why we're essentially just renaming that to component with the capital C and then lastly we want to do the dot rest so we're going to take the rest of the props and store it in a object called rest and then in our return statement we're going to return another route so we'll import that and we want to D structure or we want to pass all the props that were passed in the private route to into our new route and then we're going to call the render function again and then we're going to pass in that function that arrow function and then we're gonna render out we're gonna do the same ternary operator so we'll do return and then we'll do is logged in then we want to render out our component right because it's stored within this variable right here so component and that's why we had to capitalize all right because every component has to have a capitalized first letter so we'll do component and we want to pass in all of the props you and if we're not logged in then we need to redirect so we'll import redirect - equals slash so we'll close out that and we'll close off our route and sigh this here should be rest so we're copying the rest of the props right so let's give that a shot so I'm gonna go to where is our page f JSX and I'm first going to change this to a a one-liner or a self closing tag with the component property so here I'll do path and then component equals but it's got admin and then we'll remove this and let's change it to private route to auto import for us private route to and then change that to private route to it's save and hopefully this should work although I didn't test it out myself beforehand so let's see we're on the homepage that's fine we're not logged in so let's actually die save everything yep I know so let's go to admin and it looks like it's redirecting us to the home page but let's make sure by going to the about page first and then hitting admin perfect so it's redirecting us and then we hit login so now we're logged in and if we go to the admin page it did not load up the admin page so let's see what went wrong all right so I found the mistake guys so I accidentally did a capital o right there and if I change that it should now work hopefully let's try this out so right now we're not logged in and so I'm gonna go to the about page we'll go to the admin page we get redirected to the home page I hit login then I go to the admin page there we go we've loaded up the admin page so this is how you would set it up if you were defining your routes using the component prop and then we've got a private route as well and that's going to be used when you're defining your components or your routes using child props and I'm sure there's a way to combine all of this logic into one reusable component so that you know regardless of which method you use it's going to be able to render out the your components properly regardless of whether it's a child prop or if you're using the component prop but I think that's probably not worth our time and it's kind of outside of the scope of this this course so hopefully you guys have a decent understanding of how to set up private routes now we've tackled a few different solutions and feel free to use whichever one you feel most comfortable with in this section we're going to discuss URLs and really try to understand what they do and provide for us as a user and after we have a solid understanding of what URLs are and how they work we'll talk about the limitations of single page apps when it comes to URLs and we'll see how we can overcome these limitations using the HTML history API so let's start off by defining what a URL is at its basic definition a URL is just a way of identifying a unique resource on your website and by resource this can really be anything so if we had a blog site a URL could represent a unique blog post or if we owned a ecommerce site URL could represent an individual product that that store is selling so it can really represent anything and with these URLs what we can actually do is we can link directly to them or even bookmark them so that you know when you click on the link or when you go back into your bookmarks and you select that bookmark you'll always get sent to the same page and see the same exact resource that you originally saw now let's go ahead and take a look at a few web sites so that we can actually see how URLs work in practice so here I've navigated to amazon.com and so that's gonna be our URL it's gonna take us to the home page and our exact URL is technically amazon.com and then slash however when you have the slash you know for the most part it just takes it away but just know that our exact URL is technically slash which is normally the homepage for most websites now this URL is unique to the home page so anytime you navigate to amazon.com it's going to take you exactly to this page but if we scroll down and let's say we're interested in reading Harry Potter so we select this link right here it's gonna take us to a completely separate link and this link is important not because the actual you know data or information the link is important but this link is important in the sense that this link will always represent this page so anytime we ever want to navigate to this exact page and see the Harry Potter book we can just navigate to this link and this is great because if I just copy this and then I open up a new tab and just paste it in there you'll see that it loads up that exact page so this link represents this page and so if we have another website and we wanted a link to this page right here we just copy that URL and paste it in and so anytime a user clicks on that URL it's gonna take us right to this page and on top of that if we ever bookmark this page you'll see that when we actually click on our bookmarks or our favorites and click on that that favorite that we created it's gonna take us exactly back to this page and that's what URLs provide for us and this is the same across most web sites so here I've got another blog open and so if I go and click on one of the recipes so I'll just click on this super chocolaty extra small batch brownies notice first of all notice the URL so when we click on this it takes us to a new URL and this URL represents this specific blog post and so you know this is going to operate just like it does on the Amazon page so anytime we navigate to this URL it's going to take us to this exact same web page so users can bookmark this page and they won't get navigated to the home page instead they'll get taken directly to this page now it's important to understand with a web site like Amazon which is what's referred to as a multi-page app it's not a single page app like the ones we've been working on with react and same with this blog right these are all multi-page apps so if we ever navigate to a different URL what happens is the web browser first of all is going to send a get request to their back-end server and it's gonna ask for this exact URL so whatever page HTML file that represents that specific URL is going to get sent back to us we're gonna reload the page and then it's gonna display that new HTML file and we can actually prove that so if I go back to the home page I'm just going to open up our developer console and I'm gonna move this down forget how to do that here we go and here we can go into the network's tab so this is going to see all the network related requests that our web browser is sending and we want to go into the doc tab so this is going to look for a very specific type of request and what I want to do is I want to just hit refresh real quick and you'll notice that you know we sent a request back to the web server and this is the main request right here so this is just asking for the home page and if I go into the headers you'll see that we sent a request for you know HTTP colon slash slash amazon.com slash ignore the ref equals nav slash logo just remember we're still on the home page but Amazon does a few extra things because it's such a big website and they add you know a few extra features so ignore that just think of it as we're just navigating to slash so we sent a request back to their new back-end web server asking for this exact web page and what happens is the web server responds and we can see the response under the response tab with this HTML file so this is the HTML file that got sent to our web browser and this is the exact HTML file that's loaded and we're looking at right now so what I'm gonna do now is I'm going to actually clear out all of this so this is going to clear all of that so we have an empty box right here and I'm gonna click on a link on this webpage so we'll go back to the Harry Potter and we'll see what happens when it comes to network related requests so I'm gonna click this hopefully you noticed one thing first of all we can already tell that the page refreshed okay and so that's the expected behavior when we navigate to a different URL because we're gonna load up a new HTML file so we are refreshing everything and click on the first link right here and you'll see the requests that we made so we sent a request to that exact URL that's up here to their back-end server saying can you please give us this HTML file and the server responded back with the exact HTML file so this is how a multi-page app works every URL represents essentially a different HTML file that the web server is going to load and send to our web browser who can then load it up alright so keep in mind that the way traditional apps work and this is important whenever you change URLs it's going to trigger a request to the back-end server and reload our web page alright and this creates problems for us when we're building out single page apps right because first of all when we utilize JavaScript and Ajax to automatically you know render the content of our of our application we are never actually loading a new page that's how single page apps work we're always on the same page the same HTML file we're just loading different things using javascript and ajax and in a single page application we never actually want to refresh the page because if you recall whenever we perform a refresh of the page we're clearing all of our states so we lose all state of our application and it's gonna be almost as if the user first navigated to our page so we never ever want to refresh when we perform or when we operate in a single page application however this creates a few problems because if we're never refreshing our page and because JavaScript and Ajax are kind of handling the responsibility of loading different pages what happens is we never actually update the URL right because we're never going to a different we're never going or navigating to a different URL because we're never actually sending a request back to their back-end server asking for a new HTML file and this creates a problem because if you recall each resource on a website is traditionally assigned a URL just like this Harry Potter book has this URL just like this blog post has this URL so if we were building a Amazon clone with as a single page app technically every single book or item within the store instead of being loaded up by going to a different URL whenever a user would click on a book in a single page app it would just send a request back to the back-end server not asking for a new HTML file but instead asking just for the contents of what needs to be loaded and then JavaScript will take over and just load that data so we would never actually be changing URLs and so you could think of it as our URL would always look like this amazon.com no matter what links we clicked on no matter what items we look at will always be on amazon.com because we're never actually asking for another resource we're never changing the URL or anything like that and that can create lots of issues for users because if the URL is always amazon.com no matter what they go to if they bookmark the page they're always bookmarking amazon.com right and if we go to amazon.com take us to the homepage so no matter what item they bookmark they'll always get bit sent back to the homepage and that's going to create a bad user experience because then they essentially essentially defeats the purpose of bookmarks in this case and so that's really the fundamental flaw of single page apps is that we lose that ability to you know link to specific pages in our application because they're technically aren't there aren't truly any different pages in our application it's just kind of a made-up construct that you know Java Script will just load up different contents that represent different pages but there aren't really different pages in our single page app and so that's the main that's one of the main differences between a multi page app in a single page app and that creates problems and so this section you know we're gonna focus on how we can get around this problem by utilizing the HTML history API and you know before I actually go into you know what that history API is and you know how it works just know that really it's just there to kind of make our single page app operate a little bit more like a multi page app where we have different URLs for different pages but at the end of the day it's still a single page app so there's still only one HTML file we ever get back from our back-end server and that HTML file will still have JavaScript and Ajax you know loading different data but with the history API will have different URLs that users can you know bookmark and provide links to and it'll take them to that exact resource that they're looking for and keep in mind also in a single page app if we don't implement the history API it also breaks the forward and back functionality because if I select a you know if I go back to this Harry Potter book and I hit back it takes me back to this page but I can go forward and it takes me back to Harry Potter however if we didn't have the URLs updating like that if I hit back from this Harry Potter book it's not going to take us back to the Amazon homepage because the URL would technically still be amazon.com it would still it would take us to the previous website we were on before we navigated to amazon.com so that's another and why that's just another example of how you know single page apps have limitations but once again you know we can overcome all of those limitations using the history API and so that's what we're gonna tackle in the next video and I'll see you guys there all right guys so in this video we're gonna talk about the history API and what the history API does is it gives us the ability to modify a website's URL without a full page refresh so this is obviously super useful for single page apps to kind of navigate around the limitations that I discussed in the previous video where we want to be able to give users the ability to link to specific portions of our website or specific pages as well as bookmark pages so that they can return back to the same resource that they were originally looking at and to actually demonstrate this what I want to do is I want to take a look at a well-known single page application and that is I'm gonna go to twitter.com alright and so this is a single page app and we can actually confirm that I'm just based off the behavior so if we go to our network's tab again and we go into the doc subfolder whatever you want to call it you'll see that we sent a get request for twitter.com and that's exactly what we did we got the page technically we get redirected to the URL of twitter.com slash Explorer but don't worry about that so just know that we sent a request back to the server and we got the initial page now if we clear this out so that we only see new requests that come in if I select or if I search for let's say Aaron Rogers right let's see if he's on Twitter looks like he is and if I select this it takes us to a new URL so it takes us to twitter.com slash Aaron Rodgers 12 but notice how under this Doc's section we sent no new requests right and so that's because this is a single page app so we're not going to send another get request to receive a new HTML page for twitter.com slash Aaron Rodgers instead what we did was we sent a request using JavaScript using like the fetch API and we just retrieved some data right and that data is gonna be all the data that's being displayed here so it's gonna get the data about Rogers you know most recent posts and things like that and then it's going to dynamically load that onto the same HTML page that we've been working on and you can see the other requests by going to xhr and fetch so you can see all the other fetch requests that this page sent down so there's a ton and so that's how we see all this new data about Aaron Rodgers now to actually show you how the history API works I'm just gonna click on a few links so we're gonna go to like NFL I'm just gonna make sure we navigate to a whole bunch of different pages on their website maybe ESPN now we take a look at that and then let's see what's trending Dennis Miller whoever that is he's trending alright and then let's check our stimulus payments okay so we've visited several pages now on their website now to actually interact with the history API I'm just gonna clear this out so this is just some warning I'm getting I think it's due to my antivirus so it's blocking something on this website kind of annoying but I'm just gonna clear that out now to actually retrieve the history object just type in history and you'll see that it's gonna autocomplete and so if I you just hit enter whoops there you go ahead enter you'll see that this is our history object right and I'm just gonna scroll up so it doesn't keep going down and you'll notice that here we've got some data so it's got it's storing some kind of state and we also got the actual path so this is going to match up with the actual URL and if we go under proto I think under object here nope that's not what I'm looking for here we go so under here you could see that all the different methods that we have associated with this history object so it looks like we have a go method we've got a back method I think you can guess what the back method does we've got the forward method push date and replace date so let's try these methods out so if we want to navigate backwards one page I can type in history dot back and let's see what happens there you go look it took us back to the Dennis Miller page so that's how we can use a history API to navigate so if we want to move forward now we can type in history dot forward and remember you can only do forward if you've moved back at least once I hit forward it took us back to the stimulus payment page we can also see just how big our history object is by typing in history dot length oh that's not a function we just want history dot length and you can see there's a length of 7 so we visit essentially seven different pages or URLs and so that's why our length is seven now we can also use the go method so if I type in history dot go and now we can pass in a value now this value is gonna determine essentially the direction we want to move in so if it's a negative value it's gonna go back a certain number of pages if it's a positive value it's gonna go forward a number of pages so if I type in negative one it's gonna go back to the previous page essentially one page so this is the equivalent of doing a dot back right so I type that in it goes back one page and I can even go back three more pages if I hit this and so that takes us back all the way back to Aaron Rodgers and if I want to go forward and I can type in four and that's gonna take us back to the stimulus payment page so that's how we use the history API to move backwards and forwards but now we need to actually get to the part where we can essentially create a new URL right and so the way we actually push something on to the history stack push a new URL onto the history stack is by doing history dot push State do push state and here you know I can I tested this out obviously before I record it so you can see what I entered but when you do push state we gotta pass them three values so the first value is we pass in a object and this can be any object with any kind of data but this is just data that you may want to get passed to the new page that you want to load of the new URL so you can technically leave this blank but let's say we did want to give some data like let's say the user is I don't know in dark mode so dark mode is set to true right so we're gonna pass this object to the new page and the new page can do whatever they want with the data they can just drop it if they want to but we can just pass some kind of data in that's all that matters we can leave this blank if we want to as well and that's probably what I'm gonna do the next thing we have to pass in is a title we don't really use this so just kind of leave that blank for now and then lastly we need to pass in what the new URL is gonna be so if we want to go to slash Tom Brady this is going to take us to twitter.com slash Tom Brady so let's hit enter and let's see what happens okay so it looks like nothing happened on this page but notice the URL at the top right we changed the URL to twitter.com slash Tom Brady if I do a history length you can see that we now have a length of eight so we push something onto the stack and so that's how we add a new URL on to the history stack so in the previous section we've actually been interacting with the history API without even knowing it and that's what reactive Riyadh sorry react router is for react router uses the history API in the backend so we never directly interacted with it but react router makes use of the history API and that's really what it all it's doing is that you know if you recall when we worked with the react router we had like like a link tag right our or a route no so we had like a link tag and so when a user clicked on a link tag guess what's happening react router all it's doing is it's doing a history push State and it's pushing in the new link and then once we push the new link we have the react we have the route tags that will look for the new link and then determine what components it wants to load and that's really all that react router is doing there's one more method I want to cover with history so if we do history dot let's do instead of push date let's do replace date I'm gonna show you what the difference is so if I do replace date I'm gonna pass in an empty object we're not only gonna use that pass in an empty title and then finally I'm gonna pass in let's say let's just say gibberish some kind of gibberish doesn't really matter what we're passing in okay and so when I hit enter now you notice I passed in the new URL but if I type in history dot length notice that it's still 8 right so what replaced 8 does is it replaces the current URL in the stack with this new URL and that's obviously different from push date which I mean it keeps the old URL but we just push a new URL onto the stack so push date will increase the length of the history object replaced 8 will not because it's just replacing the current all right so I mean that's all we really have to cover when it comes to the history API and the next video will will create like a little test react project and I'll show you how we can use the history API to actually navigate users around and not just by using a traditional link tag and there's scenarios where you may want to do that where maybe you a user clicks a button not necessarily a link or some function gets called and we want to based off of different criterias in our in the current state of application load up a different URL well we can do that by using the history API and react router provides us a way to do that so I'll show you guys how to use that and how to integrate react react react router with all of this all right so I'll see you guys in the next video and we'll get started on that ok guys so now that we understand how the history API works I want to show you guys how the history API interacts with react as well as react router ok so what I have is an empty project I've already deleted the source files and so we're gonna create a simple it's not even a project we're just going to create a little demo to kind of show you how to integrate the history API into your projects so here I'm going to do source and we're just going to create a new file that's going to be our index thas file you import react Rotterdam and will render our app component so we'll do not react Dom got render define our app component in a second all right so do you new file and then make our app component and let's open up our terminal I know we're gonna have to use react router down so let's just install that now you you and we'll do an NPM start well let's make sure we save everything first oops it looks like we have an error so we need to make sure we import our app component you you all right so now we've got our empty application and what I'm gonna do is I'm gonna set up a few routes for now and basically we're just gonna make a simple guessing game where the user is going to be asked to input something it's just some piece of text and if it matches a specific keyword then we're gonna say they've won that's it okay and so we'll import react route or Dom and I'll just do that automatically by going into our return statement here you oops and we want to import browser router and we'll wrap our entire application with that save that and let's create our pages so we're going to have one for our home page we'll have one we'll call this the game page we'll have a winner page so the homepage will just have a link that will say if you don't want to play the game go to the game page and the game page will have the actual game and if the user wins we're going to navigate them to the winner page you let's go back here and let's define a few routes okay so make sure you import route from rather dumb and will say if the path equals and we'll say just a slash make sure to give it the exact attribute then we want to load the home component the on page component Cape so let's import homepage you you and I'm going to copy this two more times and so we'll have a game that's going to load the game page and then finally we'll have a winner and that's going to be the winner page you you you then let's just create some dummy content within each of these components so we'll just say game page here we'll say homepage you you and then finally this one's gonna just say winter page all right so we've got all of our components set up now now let's just put in some let's just put in some data in our app component or sorry in our home component so that the user can get to the game page so here no how do we now going back to our react router section how do we navigate a user from one page to another or from one URL to another well we do that with a simple link tag so I'm actually going to wrap this in an h1 tag say homepage and then we'll put in the link tag so first we have to import it from react router Daum and we'll say to and they want to go to the game page slash game we'll say let's play a game this will create a link that a user can click on it's gonna take him to the slash game URL which is going to load the game page let's hit save all and let's take a look at our application so we've got our homepage notice our URL so we're at the /url and then we've got you know the link that says let's play a game so if I select this button takes us to the game page so it looks like react router automatically updates the URL for us and the way it does that is by using the history API so all along you know since we've covered the react router within this course we have been working with the history API except we haven't been touching it directly instead react router kind of abstracts all of that details away from us and handles that on the back end so that we don't have to all right so we know that we can update the URL by saying go by using a link tag and when the user clicks that link it'll update the URL to the designated URL that's assigned to the two attribute all right and so that's cool however you'll find that if you need to update the URL in certain situations a link tag just won't be usable and I'm gonna give you an example of that and I'm gonna show you how we can more closely modify the URL and the history API so let's build out our game application and so here this is just going to be what I'm gonna do is I'm gonna put an h1 and this is gonna say game page so that the user know he's he's on the game page and we want a simple input tag and we also want a button and so this is going to be a controlled input so we want to make sure we put some state on that guy so we'll do Const and we'll say guess because it's going to represent their the users guess you you you and remember to make this control we're going to hard-code the value to guess and we're going to put a on change event handler passing the event and say that set yes you a target value let's give that a shot and let's well let's make sure we put some tests and some text on the buttons will do guess okay and so we've got this let's just make sure that it's updating fine all right it looks like it's working hi and so now what we want to do is when the user guesses a specific word and we can pick any words I'm gonna pick chocolate when they get chocolate it should take him to the winner page if they guess wrong then nothing should happen so what we want to do is we want to put an on-click event handler you and we'll say handle guess quicks all you can't handle guess and we'll say that when he clicks this button well the first thing we want to do is if yes equals equals equals and then well our string is going to be chocolate so if the user guesses that then there You've one and here we need to define what we want to do when the user guesses correctly and so if we so we wonder what we want to do is we want to set the link to instead of slash game we want to move them to slash winner and that's gonna load the winner component so how do we actually do that right because the only way we know using react route or how to navigate between URLs is to specify a link tag and so if we you know how do we put in a link tag right I within a conditional like this we can so you might think well what happens if we wrap the button in a link tag and I'm gonna tell you that right now that's not gonna work and I think you know exactly why that's not gonna work so if we do two equals slash winner and then slap this button right in there what do you think's gonna happen guys well if I guess wrong as soon as I click this button right it thinks I'm clicking on the link and it takes us to the winner page that's not what we want to do right because we only wanted to navigate to the winner URL when we guessed chocolate so this is not going to be an acceptable solution so instead what we have to do is we have to UM work with the history API and we've learned you know we can do that so to access the history API you know it's part of the window object right so if we go into our console again and let me make this bigger for you guys if I type in history it's checking for any you know parameters on the window object so I can just type in history directly however that's the same thing as me typing in window dot history right because it belongs on the window object so that's actually where it resides so we can access it by typing window dot history dot what we what do we want to do push state right so that's how we push in a new URL onto the stack and we got a past in three things an object we don't really care about the data we're passing so who cares a title we'll just leave that empty and then finally the URL we want to go to so we want to go to slash winner you now let's hit save and let's give this a try while we're already on the winner page we might go to the game page okay so if I guess wrong nothing happens if I guess chocolate let's see what happens okay so we see that the URL updated but we didn't load the winner the winner page now it could be that I made a typo but I already know why this didn't work and the reason why is we're accessing the history object directly and we don't want to do that because we're using react route or react router wants to make sure that it's responsible for handling the history objects so it handles it on the backend and provides us a nice little API to work with it so that we don't have to touch it directly so if we want to actually store a reference to the history object that the react router has created for us we actually have a special hook for that and so we can do const and we'll call this history and I think it's called use history right makes sense so we'll import that and we don't have to pass it in any parameters and what I want to do is I just want to do a consult out log and let's just check out this history object right now we're on the winner page we want to go back to the game page okay and so let's take a look at the history object that I printed out and hopefully you notice something this doesn't look like the regular history API object right because here we have a push method but if you recall for working with the history object you know we usually had to do push State and that doesn't seem to be here I mean we do have go we have go back but it was just called back on the regular history API so this looks to be like a custom history object which is kind of what it is because react router is kind of abstracting all of that and giving us nice convenient methods to work with and if we actually do a history this isn't going to grab the actual history object you'll see that this is the actual history object and they both have a length of six so they seem to be related but not really because if I do because if I do a windowed history dot push state nothing really happens when I move to that winner page so we have to keep in mind that you know we don't want to touch this history object we only want to touch this history object which is owned by react router and it's going to make sure that whenever the u all changes it's going to make sure that the state of our application updates accordingly so we're gonna remove this we don't need that instead we're going to call on reference this history object so type in history dot and then looks look at the different methods so we probably want push and here we don't need to pass in the three parameters instead all we have to do is just pass in the new URL so we want to go to winner hit save so now let's give this a shot so if I type in chocolate it guess let's see what happens takes us to the winner page so that's how we operate or interact with the history API within a react and react router application okay so keep that in mind anytime you're working with react router make sure you use the history object that it's creating for us and you're not manipulating the history object directly
Info
Channel: Sanjeev Thiyagarajan
Views: 7,354
Rating: 4.9709091 out of 5
Keywords: react, router, web, development, route, hooks, url, history, api, reactjs, javascript, crash, course, programming, tutorial
Id: KaoyIX-X69g
Channel Id: undefined
Length: 111min 11sec (6671 seconds)
Published: Tue Jun 09 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.