React Routing, A Complete Guide To Routing In React

In this tutorial we will learn React routing with example, React Routing is a small task but very important for the single page application. By using React routing you will be able to switch page and after refresh the page will still same. So let’s get started react routing with example

Create React App

Before get started React Routing in your React Application, We need a React Project. If you don’t know how to create a new project. Follow this tutorial.

Step 1 – Install a React Router

Run the below command will install the react-router-dom package

npm install --save react-router-dom

Step 2 – Create Components

Next, We will create three components, you can create more as per your requirement. To create components open App.js file and put the below code

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>App...</h1>
         </div>
      )
   }
}
export default App;

class Home extends React.Component {
   render() {
      return (
         <div>
            <h1>Home...</h1>
         </div>
      )
   }
}
export default Home;

class About extends React.Component {
   render() {
      return (
         <div>
            <h1>About...</h1>
         </div>
      )
   }
}
export default About;

Step 3 – Import Router

Import the router in the index.js file

import { Route, Link, BrowserRouter as Router } from 'react-router-dom';

Step 4 – Add Route

Open index.js file and add the route and navigation

ReactDOM.render((
    <Router>
    	<ul>
    		<li><Link to={'/'} >Home</Link></li>
    		<li><Link to={'/about'} >About</Link></li>
    	</ul>
		<Route exact path="/" component={Home} />
		<Route exact path="/about" component={About} />	
	</Router>
), document.getElementById('root'));

We are using Link insted of a tag

Here we have added exact prop. What is exact prop? Why we use this? So here is your answer, “/” slash is same in both path, So it renders both components to stop this behavior we use the exact prop.

After above changes our index.js file will looks like this

import React from 'react';
import ReactDOM from 'react-dom';
import { Route, BrowserRouter as Router } from 'react-router-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';

ReactDOM.render((
    <Router>
	    <ul>
	        <li><Link to={'/'} >Home</Link></li>
	        <li><Link to={'/about'} >About</Link></li>
	    </ul>
	    <Route exact path="/" component={Home} />
	    <Route exact path="/about" component={About} />	
	</Router>
), document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

404 page

Redirect unmatch request to notfound page. You need to import the component, then you can remove the path attribute altogether.

Example:

import { Route, Switch, BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render((
    <Router>
	    <ul>
	        <li><Link to={'/app/'} >Home</Link></li>
	        <li><Link to={'/app/about'} >About</Link></li>
	    </ul>
	    <Switch>
	    	<Route exact path="/app/" component={Home} />
	    	<Route exact path="/app/about" component={About} />	
	    	<Route component={NoMatchComponent} />
	    </Switch>
	</Router>
), document.getElementById('root'));

Running the App

Run application using npm start. Congrats!! See, it was easy.

Preview

React routing application preview

Recommended Post

18 Comments

  1. cbd for sale said:

    Needed to write you this very small word to help thank you very much yet again with your wonderful views you have shared on this site. This has been simply tremendously open-handed with you to present unreservedly what most people would have sold for an electronic book to help with making some profit on their own, primarily seeing that you might well have tried it in the event you wanted. Those techniques likewise worked to become a great way to recognize that someone else have the same passion similar to my very own to see somewhat more with reference to this problem. I know there are some more pleasurable situations up front for people who see your website. https://nujemznuedi.online/

    January 7, 2021
    Reply
  2. paxil tablets said:

    I am also commenting to let you know of the helpful encounter my friend’s daughter found reading through your web page. She figured out numerous issues, not to mention what it’s like to have an amazing giving mood to have most people really easily know selected impossible subject areas. You really exceeded our own expectations. Many thanks for imparting the invaluable, safe, explanatory and even easy thoughts on the topic to Janet. https://paxilparoxetines.com/

    January 9, 2021
    Reply
  3. seroquel no rx said:

    I’m commenting to let you know of the great encounter my friend’s daughter found reading your web page. She figured out numerous issues, not to mention what it’s like to have a wonderful giving mood to have men and women really easily have an understanding of selected hard to do subject areas. You really exceeded our own expectations. Many thanks for imparting the interesting, safe, explanatory and even easy thoughts on the topic to Janet. https://seroquelquetiapine.com/#

    January 10, 2021
    Reply
  4. Beryl said:

    You really make it seem really easy with your presentation however I in finding this matter
    to be actually one thing which I feel I would by no means understand.

    It sort of feels too complex and extremely broad for me. I am
    having a look ahead for your subsequent post, I’ll attempt to get the dangle of
    it!

    My blog – cheap flights

    January 31, 2021
    Reply
  5. Nannie said:

    Article writing is also a fun, if you be familiar with afterward you can write if not
    it is complicated to write.

    My web-site cheap flights

    January 31, 2021
    Reply
  6. Theda said:

    I’m gone to inform my little brother, that he should also pay a quick
    visit this blog on regular basis to take updated from newest information.

    my web-site; cheap flights

    January 31, 2021
    Reply
  7. Daniela said:

    Helpful info. Lucky me I discovered your site by chance, and I
    am shocked why this twist of fate didn’t came about earlier!
    I bookmarked it.

    Also visit my blog post :: cheap flights

    February 1, 2021
    Reply
  8. Trent said:

    Great blog! Is your theme custom made or did you download it
    from somewhere? A design like yours with a few simple adjustements would really make my blog jump out.
    Please let me know where you got your design. Bless you

    Check out my webpage; cheap flights

    February 1, 2021
    Reply
  9. Angelica said:

    I couldn’t resist commenting. Perfectly written!

    Here is my blog – cheap flights

    February 1, 2021
    Reply
  10. Crystal said:

    Hi i am kavin, its my first time to commenting anyplace, when i read this paragraph i thought i could also make comment
    due to this good paragraph.

    my site: cheap flights (tinyurl.com)

    February 2, 2021
    Reply
  11. Bridget said:

    I have been surfing online greater than three hours these
    days, but I never discovered any interesting article like yours.
    It’s beautiful worth sufficient for me. Personally, if all website owners
    and bloggers made good content material as you probably did, the web will be much more
    useful than ever before.

    Feel free to visit my blog: cheap flights

    February 2, 2021
    Reply
  12. Jesse said:

    It is in point of fact a nice and useful piece of info.
    I’m satisfied that you simply shared this useful information with us.
    Please keep us up to date like this. Thanks for sharing.

    Feel free to visit my web-site: cheap flights;
    http://tinyurl.com,

    February 3, 2021
    Reply
  13. Korey said:

    Hey There. I discovered your blog the usage of msn. This is
    a really smartly written article. I’ll be sure to bookmark it
    and return to learn more of your helpful info. Thank you for the post.
    I will definitely return.

    Also visit my web blog – cheap flights (http://tinyurl.com)

    February 12, 2021
    Reply
  14. Corine Gordner said:

    I am new to Joomla and don’t know how to add a link from a Joomla website to mine. I looged into administrator section and can’t find any that will let me put my link in the footer of the pages..

    February 19, 2021
    Reply
  15. Freya said:

    Hi there very cool site!! Guy .. Excellent ..
    Wonderful .. I will bookmark your site and take the
    feeds also? I am glad to seek out a lot of helpful info right here in the submit,
    we’d like develop more techniques on this regard, thanks for sharing.

    . . . . .

    My page: Leanna

    February 23, 2021
    Reply
  16. Agueda said:

    Decimal Odds basically say that you will get the sum
    of the quantity you would get in return for a $1 bet.

    My web blog … read more

    February 24, 2021
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *