React Router is commonly used to make different routes for pages in React Applications.
We just released a crash course on the freeCodeCamp.org YouTube channel that will teach you how to create routes in your React applications.
Piyush Agarwal developed this course. Piyush is a prolific course creator on his YouTube channel and is very experienced with React.
This course covers BrowserRouter, Switch, Nesting Routes, and Redirecting Routes. It also covers match and history props, including useHistory, useParams, useLocation, and useRouteMatch Hooks.
Here are the topics covered in this course:
- Initialize new React App
- Header Component
- React Router Installation
- Creating Routes
- Testing Routes
- 'exact' prop
- Switch Tag
- Link Tag
- basename prop
- forceRefresh Prop
- scroll to top on route change
- 404 Not Found Page
- Access URL Params
- useParams Hook
- useLocation Hook
- Redirecting in React Router
- useHistory Hook
- Nested Routing
Watch the full course below or on the freeCodeCamp.org YouTube channel (1-hour watch).
React router is commonly used to create different routes for pages in react applications.
This course will teach you how to use react router to create your own routes in react, we're going to learn about react router, and its different concepts such as creating different routes for different pages in react.
Also, we're going to learn how to nest a route of a page under another page.
hooks like US history, use params, use locations and use route match, also how to fetch a query string in form of a variable from the URL.
So let's get started.
Okay, so let's start by creating a new react app.
I'm going to type NP x create react app, and the name of our app, which I'm going to give react router tutorial.
Now what is going to do, it's going to go to NPM website or NPM repository and going to take all of the things needed to create a new react app.
And it's going to put all of those things into this folder, React router tutorial, it's going to find all of the dependencies that we need to create our react app.
And it's going to basically initialize a boilerplate code for our react app.
Alright, so it has successfully initialized our new react app.
Now we need to switch to that folder, what we can do is either we can type cd, and the name of the folder, you can switch this way.
Or what you can do is you can open that folder in VS code, which in my case is this folder.
And I'm going to select this folder.
So here we go.
I folder has been opened in the VS code successfully.
So what I'm going to do now is I'm going to type NPM start.
So it's going to start our react app.
Here's our react app running successfully.
So what I'm going to do now is I'm going to go I'm going to go to the src folder.
And I'm going to get rid of those things that we don't need this, this, this and this, we're going to get rid of these four files.
And we're going to remove the places that they were being used.
So over here.
And we're going to get rid of all of these styles.
Inside app j s, app dot j s, I'm going to get rid of this.
Get rid of logo.
And now you'll see that our app will have nothing to show.
Me refresh it.
Yep, there you go.
It's an empty page.
Okay, so what I'll do now is I'm going to type h1, h1, react, router Dom tutorial, for this react router tutorial.
Let's save this and see.
Yes, it has successfully rendered this over here.
So let's create a different component for header.
When you create a new component called a new folder called components, it's not necessary to create a separate folder for components, but it's a good practice.
I'm going to create a different component for header dot j, s.
And I'm going to type our A, F, C underscore RFC and press Enter.
And let's copy the same thing.
Over here we go.
Let's first center align this thing.
And then we're going to start with our tutorial.
So I'm going to give it a few of the styles in app dot CSS.
I'm going to get rid our display flex and justify content.
I mean to say align items to center and flex direction is going to be column because we want everything to be top down.
You know, aligned.
So yeah, here we go.
It is in the center.
So yeah, I haven't done this.
imported the header component.
header is not defined.
Let's just import it manually.
Here we go.
It should work fine now.
Yep, here we go.
It's working fine.
So now we're going to install react router DOM.
So I'm going to open a new terminal and type NPM I react router DOM.
And you know what I'm gonna go to header and get rid of this dev Let's use the React fragment.
So if you don't know what react fragment is, you can watch my previous video on eight clean code practices in react, it's going to help you a lot 2000 years later, or it's finally a react router Dom has installed successfully.
So I'm going to go to my app JS component.
And to use our react router DOM, what we'll need to do is we're going to have to cover this whole react app in something called browser router, browser router, which comes from react router DOM, so you can see it has auto imported.
So I'm going to pull off my app in this.
Alright, here we go.
Let's close this terminal.
I think I'm going to have to restart my application.
So let me just do that quickly.
Alright, it's fine now.
So what are we what are we going to do next is we're going to create different different routes for different different pages that we're going to work with.
So let's create a route for homepage about page and profile page.
Yeah, so I'm going to type route and press Enter.
And you can see route has auto imported from VS code coming from react router, Dom VS code has auto imported it.
So I'm going to give it a path.
This is going to be your homepage.
So it's going to be this.
And we have to give it a component, which we'll create in a second.
So let's duplicate these paths.
Another one will be for about.
And the third one will be for profile.
So let's create these pages.
First, I'm going to create a new folder with the name of pages.
Home dot j s, I'm going to create a file called about dot j s.
And the third file will be profile dot j s.
Next, let me quickly write some code inside of this type homepage.
Remove these divs and add h1.
Next, same thing with the about page.
And the profile page.
All right, good.
So we have created all of our three routes.
Now let's test these routes if these are working or not.
So let me save my app real quick.
Okay, there's an ad a worse theater.
Okay, we haven't even the components, obviously.
So let's just give this home.
Go Oh, sorry.
My bad, we have to import all of these components first.
So import home from slash home.
And I'm going to do for about and profile as well.
So about and profile.
Let me just bow and put off five.
Here we go.
So we have created three routes.
This is how you create a route in react by using react router DOM.
So you can see it's currently in the root folder, I mean, in the root path.
So it's giving us homepage.
Let's go to the about page route.
There we go it giving us about but you can see the homepage is also appearing here and about page is also appearing here.
Why is that happening? Because you can see it, it has about page as well.
And this route as well.
In this init spot, it has route as well.
So what we can do is we can type exact, so it's gonna go exactly to this path and not nowhere else.
So if it type about it's going to click open about page.
And if you type profile, it's going to go to work.
Okay, I have made this mistake.
Yeah, now it's gonna work fine.
If I go to profile page, it's gonna open the profile page.
Another thing which you can do apart from exact is you can use something called switch.
So if I type switch over here, and we're going to take all of these three inside of the switch, and I've imported the switch from react router DOM.
So is what switch does is when you go to a particular path, let me remove this exact from here.
So it's gonna find whatever it finds first is gonna stop there.
For example, it has written slash profile.
So it has found the slash path First, it has matched this path slash with this.
So it is found the homepage is going to render if we use Switch Murphy type exact, then we're not going to have the same problem now.
You can see it's rendering the profile.
Now, let me type about.
Alright, here we go about page.
All right, one more thing.
So we don't need to manually type this in the URL.
So what can we do to go to another page, in the traditional web development in the HTML, we use something called a tag to go to a different page.
So we can use that over here as well.
But it has a disadvantage, what disadvantage is there, when we click on this a tag, it's going to refresh our page, let me demonstrate that thing.
So I'm going to go to our header, I'm going to create a navigation menu for our app.
Let me create an unordered list over here.
I'm going to create few list items, and have a new tag inside of it with h ref of a partner first is going to be the homepage.
So let's type slash over here and give it a name of home.
Alright, so I'm going to duplicate these multiple times, and going to give this about about seem to get a profile, and profile.
Let's save this.
And currently looks a bit ugly.
So I'm going to give it a little bit of styling.
So let's go to our app CSS.
And I'm going to add some styling to it.
Let me give this a class name.
First, I'm going to give this class name of now.
Let's give it some styles.
So I'm going to type list style type is going to be none so that it doesn't displace the bullet.
And I'm going to type width to be 500 pixels.
So I'm going to type display, flex and justify content to be spaced evenly swear it spreads around evenly.
Now you'll see Yep, it has spread around evenly.
Now let's click on one of these links.
If I'm going to click on home, you can see the page has refreshed over here.
If I click on profile, again, the page has refreshed we have reached the destination but the page has refreshed.
We don't want the page to be refreshed.
We don't want our components to be re rendered.
So what are we going to do now.
So instead of this a tag, what I'm going to do is I will use something called link, which is provided to us by react router DOM.
Let's click on this link.
And you can see it has auto imported.
So over here as well.
And lastly, yeah.
What do we can't use h ref with the link, we need to use something called to.
This is the prop that it takes.
So let's save it.
Alright, our app has reloaded.
And let's click on About.
Now you can see the page has not refreshed if I click on home, again.
So you see this is the power of react router DOM, it doesn't refresh your page, and it takes you to another page in a blink of an eye.
So let's discuss some more features of this library.
So let's see if I want a default route for our app.
Now what I mean by that is let me give a base name over here.
If I give the base name as a tutorial, and save this now you see if I click on homepage, it's going to take us to the slash tutorial.
If I click on About, it's going to take a slash tutorial slash about so this is how you can define a base name for this by typing base name equals whatever the name that you need to use.
If I click on profile, it's going to take us slash tutorial slash profile.
So this is a really powerful feature.
Let's check out another feature of the browser router.
I'm going to remove this.
And let's say for some reason, you need to use the refresh feature.
So currently, it's not refreshing our page when I'm taking it to another route.
So if I type force refresh over here, then you'll see what it does.
If I'm going to go to about you can see the page is refreshing now it's providing the force refresh forcely are apt to re render everything.
So you can use force refresh for that, which I don't think anyone needs to use.
Also, if you want to confirm every time a user goes to another route, for example, if I click on About you need to confirm it by some prompt or by some displaying some modal, what you can use is called get user confirmation.
You can type get user confirmation, and then inside of this you can write a class Message to be displayed whenever the route changes.
So I'm going to write a function inside of it by typing message, whoops message.
And it's going to take a callback is going to be an arrow function.
callback is going to take window, dot confirm.
And you can pass whatever component that you need to pass inside of it.
Let's say if you create a prompt, you can pass inside a prompt inside of it or a modal, but I don't think this is used that much as well.
So this is one of the features that you can use in react router DOM.
So let's remove this.
All right, let's move forward.
First of all, I what I want to do is the let's remove these styles from the links.
I don't want this style.
So I'm going to go to App dot CSS, and let's remove the styles by typing a removing text decoration.
And go alone will be inherited.
See, our pages are not that big.
If you go to homepage, or if you go to profile page, it's its height is not that big right now.
But let's say your your page is so big that you need to scroll down.
So whenever you change your route, what's going to happen, it's going to continue the other page from the same position.
If so what you want to do in that case, whenever you go to a different component, you can type like this.
Let me just go over here to homepage.
And you I can, what I can do is I can use use effect.
And instead of use effect, I can type window dot scroll to zero comma zero.
So it's going to do it's going to continue the other page from the top and not the previous position that page was when you were in the other component.
So this is helpful.
Okay, so next important thing is if when we type to some other route that doesn't exist, right now, let me say anything like something, and enter, you can see there's nothing being displayed over here.
We want something to display over here, like 404 error page not found something like that.
So how can we display that over here? let me create a new page for that.
I'm going to new command create a new page called not found dot j s.
Right? Let's initialize this page, A, C, press Enter.
And I'm going to give it an h1 of four books 404.
Let's save this.
Now how can we how can we use this? Now we need to go over here and close this? Yeah, we need to go over here we need to create another route, we've created another route.
In this case, we're not going to give it any of the path such as about our profile or anything, we're just going to give it a component not found.
And we're going to manually import it.
Here we go.
We've imported our not found page.
And here we go.
The message is displayed successfully.
If I go to somewhere else, it's going to still display this message.
If I go to a relevant page, like home about profile, it's not going to display any of the message.
Alright, so let's move to the next thing, which is taking parameters from the URL.
So let's say if I want a page like something called post, and we want some random post.
So we want this random ID to be accessed by us.
So what can we do over here.
So currently, it's going to show 404 not found.
So let's create a new page for our post.js.
So what we want to do is want we want to fetch this particular ID.
So let me type ID is and we're going to display the particular ID.
I'm going to give it h two over here.
Currently, it's not going to display anything if I go to post.
Okay, we haven't created that out obviously, we need to go to App j s and create another out.
Here we go.
We have created this part successfully.
Now you can see it showing us ID is equals which we can't do anything if the slash type anything.
It's going to no it's not a display anything.
So what we need to do now we're going to do is slash ID.
So now it's going to take a random ID from us.
So if I go to post now it's going to display not found because that page doesn't point needs to have an ID to display.
So let's go back to our pitch.
And now we're going to use our first hook, which is called use params.
Or we can use a match as well, let me just display, let me just demonstrate it with the match first.
So we're going to go over here D, D structure the match from here.
And now, what we're gonna do is we're gonna go over here and type match dot params.
And what what was the name of the params? It was ID, let's save this.
And let's check this out.
Here we go.
If I give this let me type random over here, and press enter.
You can see the ID is generated, and it's displayed over here.
I mean, it's not generated, we have provided it, but it's displayed over here.
Yeah, so what's the another other way to do this.
The other way to do this is using use params hook, which is provided to us by react router DOM.
So I'm going to click over here.
And you can see it has auto imported from react router DOM.
Now we don't need this, I'm gonna get rid of this.
I'm gonna use use params.
Let's first log this use params.
Let's see, what do we get inside of this.
I'm going to remove this now.
So don't get better.
All right, let's log this use params.
and inspect this, you get an object.
And this object has something called ID inside of it, which is the ID that we have passed over here.
Let me type something and press.
Here we go.
It has given us another object with ID of something.
So now, we're going to use this use params.
I'm going to type const, ID equals use params.
And we're going to D structure this ID inside of the use params.
So we have taken out this ID and we can just use this ID over here.
Let's save this.
Let's check here we go something and we give it a random number.
And here's our ID displayed successfully.
So this is how you can fetch the ID from the URL.
Now let's say we need to use a we don't want to change our route.
But we still need to use the variables from the URL.
For example, if I type question mark, and I, let's say I type name equals viewshe.
Let's say we want this name this new How can we fetch this from the URL? Is there any other way? So we're gonna use our second hook called use location, use location, and it's also provided to us by react router DOM.
So we're gonna type use location over here, let me just log this use location first.
And check what do we get inside of this? Let's go to inspect.
We get an object.
So what does this object has it has a path name.
And it has a search with the value of name equals viewshe.
Let me type something else first.
And we can type and last equals Agarwal, which is my name.
So yeah, let's see.
Now the value of search has changed to first equals fusion logic, what? Now how do we fetch these first and last variables from this search? You know, variable search object.
So what I'm going to do now, so we're going to use an inbuilt API from the browser called URL search params.
So I'm going to select it.
And I'm going to type you are l search params.
And I'm going to create an object out of it.
So I'm going to type new URL search params.
And what do we want inside of this use location, we want this search.
So let's type search.
Alright, let's take it in some variable.
Let me type const.
query equals new URL search params.
Here we go.
So how do we take out the stuff from this query? So let me just go over here and h2.
And we need to use the first and the last.
So let's first extract the first one.
So query dot get.
And in the bracket, we need to, we need to write the variable that we need to fetch from the URL.
So I'm going to type first and save this.
Let's see what happens.
Okay, here we go.
We get the page from here from the first and let's fetch the last as well.
Last, here we go.
So we can type n number of queries inside of this URL, and we can Then by using this method, use locations hook.
So that's pretty cool.
Now let's see, let's suppose you have a login feature in your app.
And you want user to access the profile only if that user logs in into your app.
So how are we going to modify our react router Dom according to that, let's find out.
We're going to go to App j s.
And we're going to create a new state, let's say login.
import the user state from react, here we go.
So by default, login will be false.
Login will have false value, because we are not logged in now admit, let me just create a button over here to log in.
But nobody has created it.
Let me just take this div and put it over here so that everything is centered.
Yes, it's centered.
So what I want is, when I tap on this login, we're going to simulate a login feature by making this log in as true and it's going to display log out then.
So on click what it should do, it should set login as the opposite value.
So if it's true, it's going to be false.
If it's false, it's going to be true.
Also, what I'll display over here is if login is true, if which means if user has successfully logged in, then it should display Whoa, what's happening? Yeah, then it should display logged out.
Otherwise, it should display login.
Let's save this.
And let's see if it's working or not.
Okay, it's working fine.
So what do we want to do over here, if our user is not logged in, he's not going to be able to access the profile page, and he's going to be redirected to the home page.
So how can we achieve that, we're going to use something called redirect from react router DOM.
So let's remove this component from here.
how I'm going to do this is here, we're going to make the child component of this route.
So let's check this over here.
If login is true, if login is true, then it's going to be able to access the profile page.
Otherwise, it's gonna be redirected.
Where will it be redirected to home page.
Here we go.
Alright, let's try clicking on our profile page.
Let me go to about page and let's click on profile page.
You can see we have been redirected to homepage.
We can't access the profile page now.
But the moment we press login, and let's go to profile page.
Now we're able to access the profile page.
So it has became a protected route for our app.
If I'm inside of this profile page.
And if I press logo, let's see what happens.
It's gonna redirect us back to the homepage.
Now there's another way of doing this.
Let me show you, we can use something called US history, US history hook.
So let me just tie this over here, I'm going to remove all of this redirect stuff.
Make it a normal route now to working normally now without login.
So I'm going to, what I'm going to do is I'm going to send the log in as a parameter inside of this stuff, send the login as a params.
Let's go to profile and D structure the logging out of here.
Here we go.
And let's create a use effect.
So use the effect brands whenever our app is initialized first time.
So I'm going to take the history out of the US history hook.
So let's type US history.
I'm going to assign it to const.
It has auto imported from react router DOM, what happened? Okay, we haven't imported the US effect.
Here we go.
Alright, so what do we need to type inside of the US effect, we need to check if the user is logged in.
Or if the user is not logged in? What are we going to do if he's not logged in? Then we will use history.
dot push is going to push this path to our URL.
So it's going to push to the slash page which is our home page.
So let's try this out.
I'm at the homepage, let's go to profile page, I'm not able to access the profile page.
Now, let's log in.
And let's go to profile page.
Here we go.
We're successfully in the profile page.
And let's log out now.
Whoa, what happened? I think I have missed some.
So if we wanted to run whenever the login variable changes, so I'm gonna provide login over here and history, we're going to provide these two dependencies inside of the use effect.
Whenever these two dependencies are gonna change.
It's going to fire off this function.
Let's try again, we're going to go to profile, it's not going there.
I'm going to type I'm going to click on login.
What am I saying today? Okay, so let's go to profile now.
Here we go, we're able to access the profile page.
Let's log out.
Here we go.
We're back at the homepage, if we want to go to about page about, let's say, if the user is not logged in, is going to go to about page, if I click on profile, see it redirects us to about page.
But if you are logging in, go to profile page.
So I hope you all understood, you know this feature of react DOM.
Let's move to the next feature.
So let's discuss how can we create nested route inside of a particular page.
For example, if inside of the profile page, I want to create two routes, with the name of let's say, view profile, and edit profile, and I don't want those two routes to affect our whole react router system, we only want them to work inside of this profile page.
So let's create two new routes over here.
I'm going to remove this, let me just put it inside of this round braces and then provide react fragments to these.
Alright, let's move this.
Yeah, so I'm going to create a navbar inside of a profile page.
I'm going to create a link tag over here.
And let's say view.
And the other link tag, is gonna have heard it, edit profile, it's also we haven't created these view profile Edit Profile components yet.
So we also have to create those view profile.
Here we go.
We need to provide it to it's going to go to work.
So first of all, before doing all of this, let's create our route and the component first to read we have these errors out of the way.
So I'm going to go below this.
And as usual, we're going to create a switch.
x even has auto imported or not, yes, it has.
Alright, we need to create two routes.
Route one will have path of slash, view profile.
And it has it's gonna have some component which I'm going to create next.
And the other one will be the Edit Profile.
Let's create those two components first.
Review, proof filed or GS made a spelling mistake.
reprofiled rj What the heck.
br o f i l e.
Let's create this RFC.
And I'm gonna give it a h two and view profile page.
This component created and remediated profile image, Edit Profile page, giving this h2 as well.
Let's move on to the next thing.
Now we're going to go back to our profile page.
And over here, we're going to go and give it a to to slash Edit Profile.
And this one to the view profile.
Let's see if it works or not.
route is not defined obviously route and links are not defined yet.
So I'm going to auto import it from the VS code.
With the help of VS code here, here we go.
All of these are important now.
Alright, let's see.
What's the error over here.
Link is not defined.
Link is defined.
You can see link is defined over here.
Let's meet Let me refresh this.
Yep, it's working fine.
Let's go to the profile.
Okay, we have to log in first and let's go to profile.
Okay, we have view profile and edit profile over here.
But it's not working now.
But why is it not working now? Because we have already created our routes over here.
So what do we need to do? So what do we need to use now? Because we're going to use something called use route, match hook, use route match.
So this is the hook that we're gonna use to help us, you know, move the components inside of other component.
So let me type const.
And I'm going to take out something called path and something called URL from inside of this thing.
So let's see how can we use this path and URL, first of all, we want to go to, we don't want to go to View profile, because it's taking us to slash edit profile or slash view profile, we want to go for example, if your add the profile, we want to take the current URL, and then append the view profile after it.
So what I'm going to type over here, first of all, I'm going to remove this standard string tags, and I'm going to use backticks.
Okay, so now we need to provide a variable inside of it.
Which will be URL.
Yep, now it's gonna work fine.
And the same over here.
URL, and I'm going to remove the string and give it a backtick.
Just like that.
So this is how it's going to work.
And what here as well.
Okay, we haven't given the component, prop.
So it's gonna be view, view, bureau file.
So it's not auto importing.
Let me just import it over here.
Your profile from have to go one step back and inside of the components and view profile, same with the Edit Profile as well as your profile, I should work now.
Then we would have component component of edit, profile.
So here we go.
We have created our two routes over here.
So what do we need to do now, we need to provide it the PATH variable.
But it's going to know that the current URL that we are in the current path that we are in, we only need to append this particular you, you know, URL to that URL, I mean path to that URL, or the route to that URL.
So I'm going to type path over here, similarly, but over here, just like that, you know, the drill.
I'm going to do this created a back tick.
Over here as well.
Now, everything should work fine.
Let's try it out.
If I click on View profile, it's going to take us to view profile page, you can see slash profile slash view profile.
And if I click on Edit Profile, it's going to take us to edit profile page.
And all of the other routes are working absolutely fine.
There we go.
If I click on logout, it's going to take us to the home page.
So thank you all for watching this react router Dom tutorial.
I hope you all understood what are the concept that I explained to you in this video.
If you have any confusion, you can comment down below to ask me I'll reply to you as soon as possible.