Protected Routes in React using React Router

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey this is my Carnac if you are watching practical examples in react today we're going to implement public and protected routes using react router let's dive into some code we're running a basic react application here via code sandbox do all the react router components used in a web application should be imported from react router dump so let's go ahead and add that dependency to react router Dom let's create a component called landing page we're going to return a react component here first we import react from react we're going to export landing page as a functional component let's return some markup here and I'm going to return landing page here when I save it's going to rearrange the the markup all right going back to index we're going to import our landing page oops from the landing page and let's let's load the landing page right here and notice that landing page prints right there all right next we're going to import browser router from react router dump browser router basically gives access to the history API and keeps the UI in sync with the URL now we need to wrap our app component with browser router let's go ahead and do that alright everything still works as expected let's import route and switch from react router Dom we're going to convert landing page to a grout so let's remove landing page here we're going to create a route component and pass in landing page as a component reference to route so notice that landing page loads here anytime a route does not specify a path it will load a component regardless of what's in the URL so let's make this load only when the path equals root or slash let's try going to slash app notice what happens landing page is still loading that's because it does a prefix match and so essentially it matches on slash here and still loads landing page what we need to do is specify the exact property so that it only loads when the route is the route in this case we're going to create a component called appellee out which we'll load when we specify the app route first let's take care of returning a react component here so we are going to return react from sorry import react from react and then we're going to return or export a constant called app layout which is going to equal to a function and we're going to return some markup here let's call this back layout and on the same it's gonna reorder everything now let's go back to index and we're going to import app layout from the app layout file and let's create another route here so if I copy and paste this notice that you will get two instances of landing page I'm going to replace this with happily out and we only want appellee out to load when the path matches slash app so it disappears there now if I were to put in app it's going to load happily up if I were to remove app here and go back to the root it's gonna show landing page now what if we wanted to protect components under the app route and only make them available to users who were authenticated before we can do this let's create a file called auth is to track the login status this class will export an instance of the class so that we mimic the singleton pattern and internally we're going to create a constructor with the property called the startup gente gated and set that defaults will create a login method which will set this start authenticated to true and let's also take in a callback simulating some asynchronous operation here going back to the server and coming back and when it's done it'll call back to the color likewise let's do a logout call they call back here this is going to set authenticated to false and we're gonna call the callback and finally we're going to create an is authenticated method which is going to return the status of authenticated indicating it for logged in or not in the real world scenario you would end up managing your authentication via an interface like this that provides some abstraction so essentially you could be loading stuff from your local storage or the server side or look at your cookie etc let's go to our landing page and create a button for logging in so let's create a button here I'm gonna move this to an h1 tag and on click I would like to handle the callback right here let's reference off from now this is all lowercase because we're expecting an instance of the auth object we're going to call and we're going to call auth dot log in with a callback method that gets triggered when logging is successful we want to redirect the user to the app so we're going to use a property called history and push the app route to it this will tell the react router to change the URL to slash app and then redirect the the user to the app route so let's go ahead and click login and we have an error here that's because this is a functional component and props should be a parameter alright so let's try logging in again and notice that we go to app layout and the pad changes to app although we're redirecting to app we're not checking if the user is actually logged in so going back to index GS we're going to create a new component called protected route and this component is going to import from react it's going to input react from react and then we're simply going to export a constant called protected route which is again a functional component and we are going to return a route we need to make sure to import route before we can use this from react route or DOM and we're going to pass in component as a prop here which we will be structure and call it component with a capital C and rest of the properties that are passed in will be D structured into rest we're going to pass in all the rest of the props into route followed by a render prop which is basically a property call render and the the value for it is a functional component and we have to return our component this function gets a few props passed of it in case we wanted to pass some properties from our route definition into component so we're going to pass those along and I've made that mistake here I need to enclose this in brackets since we're D structuring or restructuring this now when I save it's gonna reorder everything now let's go back to index es so far everything loads let's import our protected route from protected route and we're going to copy that and simply replace this route here for app so let's save it so it's going to restructure everything so far everything seems to work okay now all protected route is doing is it's returning a route with the component that's passed in in our case it's the Apple a out as a render prop we also need to check if the user is actually logged in so let's import off from auth and inside of our function here we're going to check if user is authentic and if that's the case we're going to return a component else we're going to redirect the user so we're gonna return a redirect component so we need to import redirect from react router Dom we're going to render a redirect component I'm sorry a return a redirect component which will tell it to go to a specific path which is passing as an object with a property called path name now this is available in the react router documentation we're also gonna pass a state prop to it or a value for its state which tells it that we're coming in from whatever location we were trying to go to which will be passed in here to rest and then through props and finally down here let's implement a logout button in the appellee out I'm going to start out by turning this into an each one followed by adding a button component that's gonna be called logout and on click we want to call auth dot log out so let's import off from the auth file and we're gonna call off dot log out which also takes a call back and so when logout is successful we're going to call this dot props history DUP push and tell it to go back to the root now the reason history is available on props here is because we loaded it be a route so the route object or component passes in a prop called history down to landing page or to a plea out remember predicted route is still route internally and that's why we have access to this dot props dot history if we had a separate component we had created here then it would not have access to history and in that case we would need to import with router from oops from react router dump and then use that as a higher-order component let's go ahead and click log out and we have an error here and I mean the same mistake here that's not because I normally work with classes and for the purpose of this demo I had decided to use functional components so I click login and goes to AB layout and click logout goes back to landing page now the reason we see protectively a crowd are printed is because in our index TS i am printing that here so we can remove that what happens if we were to go to some random URL here i click enter nothing loads so in that case you would want to define a route which would handle every other path that's not defined and we won't basically render a 404 page in this so something like 404 not found right but when I load this oh I forgot to close this here so when I when I go to a random route that's what happens but notice what I have what happens when I go back to the route right I still see 404 not found and the reason is because we imported this component called switch but we haven't used it yet it essentially acts like a switch statement so we just want to stick it up here in between sorry around the routes and it sort of acts like a switch statement where it will stop after the first route that matches notice that the forefront found is gone it's still there if I type in some junk here we're gonna get 404 not found and now going back here login still takes us to a play out logout will take us the landing page hope you enjoyed this video if you have any questions or comments write them below and subscribe to my channel to be notified of future videos thank you [Music]
Info
Channel: freeCodeCamp.org
Views: 249,169
Rating: 4.9046631 out of 5
Keywords: react, react-router-dom, react router 4, authentication, javascript, es6, react tutorial, tutorial, react app, auth, auth tutorial, javascript tutorial, webdev, app development, lesson, try javascript, js tutorial, js, reactjs, learning, programming, programming tutorial, reactjs tutorial
Id: Y0-qdp-XBJg
Channel Id: undefined
Length: 15min 39sec (939 seconds)
Published: Tue Oct 16 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.