Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for React Router in 5 minutes
Minhazur Rahman Ratul
Minhazur Rahman RatulSubscriber

Posted on • Edited on

     

React Router in 5 minutes

React Router is the standard routing library for React. “React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. After reading this post you will become a master of react router. So let's get started.

How to use it?

Before using it, you need to install react-router-dom. So open up command line and install it.

npm i react-router-dom
Enter fullscreen modeExit fullscreen mode

After it's installed, Now we need to import some stuffs.

import{BrowserRouter,Switch,Route}from'react-router-dom'
Enter fullscreen modeExit fullscreen mode

After importing, we need to wrap our whole app with browser router or where ever you want to use router, wrap the whole thing with that. Now add this switch element in browser router.

importReactfrom"react";import{BrowserRouter,Switch,Route}from"react-router-dom";constApp=()=>{return(<><BrowserRouter><Switch><Route/></Switch></BrowserRouter></>);};exportdefaultApp;}
Enter fullscreen modeExit fullscreen mode

Now we can create routes.

importReactfrom"react";import{BrowserRouter,Switch,Route}from"react-router-dom";constApp=()=>{return(<><BrowserRouter><Switch><Routepath="/"exactcomponent={()=>{return(<><h1>Hello I am the home page</h1></>);}}/></Switch></BrowserRouter></>);};exportdefaultApp;
Enter fullscreen modeExit fullscreen mode

So as you can see here in this code, I have created a route which is for our home page cause we have specified the path which is '/'. And then, if the path is, '/' then which thing should it render, I have created a component there. You could just create a separate one then import it and then just put it 'component={here}'.

Let's create some more routes.

importReactfrom"react";import{BrowserRouter,Switch,Route,Router}from"react-router-dom";constApp=()=>{return(<><BrowserRouter><Switch><Routepath="/"exactcomponent={()=>{return(<><h1>Hello I am the home page</h1></>);}}/><Routepath="/about"component={()=>{return(<><h1>I am from the about page.</h1></>);}}/><Routepath="/blog"component={()=>{return(<><h1>I am from the blog page.</h1></>);}}/></Switch></BrowserRouter></>);};exportdefaultApp;
Enter fullscreen modeExit fullscreen mode

Now I have created multiple routes. Now we can only see the home page in the screen. How can we see the other pages? Easy! Just type 'about' after the url of your page then you will be redirected to the about page. So after writing '/about', why it is redirecting us to the about page? Cause we created the route by specifying the path which was 'about'. So when anyone will write this path, he/ she will be redirected to there. So now, it's not a cool stuff yet :(. Now we will see how can we create a awesome nav using react router. And it will be super fast. So let's create a 'Nav' component. :)

importReactfrom"react";import{Link}from"react-router-dom";constNav=()=>{return(<><Linkto="/"exact>        Home</Link><Linkto="/about"exact>        About</Link><Linkto="/blog"exact>        Blog</Link></>);};exportdefaultNav;
Enter fullscreen modeExit fullscreen mode

So this one was our nav component. Nothing so much fancy here. I have just imported 'Link' element from react-router-dom. The it takes a prop 'to' which specifies to where it should redirect. Now let's render it under our app component.

importReactfrom"react";import{BrowserRouter,Switch,Route}from"react-router-dom";importNavfrom"./Nav";constApp=()=>{return(<><Nav/><BrowserRouter><Switch><Routepath="/"exactcomponent={()=>{return(<><h1>Hello I am the home page</h1></>);}}/><Routepath="/about"component={()=>{return(<><h1>I am from the about page.</h1></>);}}/><Routepath="/blog"component={()=>{return(<><h1>I am from the blog page.</h1></>);}}/></Switch></BrowserRouter></>);};exportdefaultApp;
Enter fullscreen modeExit fullscreen mode

So now I am rendering the Nav component in the app.js But it's showing an error why!!! Haha cause we are using Link element in Nav so we have to put the nav under the BrowserRouter cause we are putting the path's of this router in our Nav. After putting it under BrowserRouter, Then it should work just fine. :)

importReactfrom"react";import{BrowserRouter,Switch,Route}from"react-router-dom";importNavfrom"./Nav";constApp=()=>{return(<><BrowserRouter><Nav/><Switch><Routepath="/"exactcomponent={()=>{return(<><h1>Hello I am the home page</h1></>);}}/><Routepath="/about"component={()=>{return(<><h1>I am from the about page.</h1></>);}}/><Routepath="/blog"component={()=>{return(<><h1>I am from the blog page.</h1></>);}}/></Switch></BrowserRouter></>);};exportdefaultApp;
Enter fullscreen modeExit fullscreen mode

Here we go, now we are getting the output just perfectly :). But a last thing how do we know in which page are we in now? So in this case, we should use NavLink instead of Link then we will have another extra prop named, 'activeClassName'. Let's make it :).

importReactfrom"react";import{NavLink}from"react-router-dom";constNav=()=>{return(<><NavLinkactiveClassName="active"to="/"exact>        Home</NavLink><NavLinkactiveClassName="active"to="/about"exact>        About</NavLink><NavLinkactiveClassName="active"to="/blog"exact>        Blog</NavLink></>);};exportdefaultNav;
Enter fullscreen modeExit fullscreen mode

I have put a active class. Which will be styled when the page is opened/ Loaded. So style it in your way how ever you want.

In routing, we are using component prop for rendering. But we have another prop which is render. So What it does? It will create the whole component again. After the page loads.

So that's all about react router hope you enjoyed that. Thanks for reading this article. If you have any issue with my post, please let me know. And make sure you follow me to recieve all the informational posts just like that one.

:)

Top comments(8)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
atulcodex profile image
🚩 Atul Prajapati 🇮🇳
HTML, CSS, Bootstrap, XML, ajax, react js, WordPress, Magento, Shopify, Photoshop, Camtasia, SEO & learning new skills every moment 👨🏼‍💻 | I believe in learning and sharing with others 🛴

I think you are learning to react from Stephen Grider, Right?

CollapseExpand
 
developeratul profile image
Minhazur Rahman Ratul
Professional Full Stack Developer | Writer (2k+ Subscribers)
  • Email
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He/Him
  • Work
    Product Developer and Designer
  • Joined

no

CollapseExpand
 
atulcodex profile image
🚩 Atul Prajapati 🇮🇳
HTML, CSS, Bootstrap, XML, ajax, react js, WordPress, Magento, Shopify, Photoshop, Camtasia, SEO & learning new skills every moment 👨🏼‍💻 | I believe in learning and sharing with others 🛴

Ok

CollapseExpand
 
lyrod profile image
Lyrod
Web developer at Freelance.
  • Location
    Nantes, France
  • Education
    BTS SIO
  • Work
    Web developer at Freelance
  • Joined

Only NavLink has activeClassName prop, right?

CollapseExpand
 
developeratul profile image
Minhazur Rahman Ratul
Professional Full Stack Developer | Writer (2k+ Subscribers)
  • Email
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He/Him
  • Work
    Product Developer and Designer
  • Joined

Yes every NavLink has this active class

CollapseExpand
 
myogeshchavan97 profile image
Yogesh Chavan
React Trainer | MERN Trainer | Full Stack Developer | JavaScript | React | Nodejs. Connect with me for mentoring session: https://www.codementor.io/@myogeshchavan97

Really explained it well. If someone wants to learn more about React Router check out my FREE React Router coursehere

CollapseExpand
 
andrewbrown profile image
Andrew Brown 🇨🇦
I make free cloud certification courses
  • Email
  • Location
    Schreiber
  • Education
    Starfleet Academy
  • Work
    CEO at ExamPro
  • Joined

Thank you for this concise tutorial.

CollapseExpand
 
enikindness profile image
Kind
WebDeveloper | Tech Blogger
  • Location
    PortHarcourt - Nigeria
  • Work
    Full-Stack Web-developer
  • Joined

Thanks man, this definitely helped❤️

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Professional Full Stack Developer | Writer (2k+ Subscribers)
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He/Him
  • Work
    Product Developer and Designer
  • Joined

More fromMinhazur Rahman Ratul

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp