React router step by step…

Md.Saiful Islam
2 min readApr 3, 2020

--

Introduction:

In this tutorial,you will learn about how to use react router,that helps you to create Single Page Application(SPA) that is most popular application right now.

What is Router?

In general, route means a method or way between start and destination place.Similarly,react router also help us to go to from one component to another component by rendering required content without refreshing full page.As a result we have a SPA easily.

Installation:

To use react router in your app,first you must install in your project by npm command —

npm install react-router-dom

Now you need to import some component from react-router-dom package in App.js folder.

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

Create Components:

For clearing your routing concept,lets create two components in src folder like as —

Home component:

About component:

Route Implement

Declare Router into your App.js file and then declare Switch component into Router component. finally create a route for a specific view.

function App() {
return (
<div>
<Router>
<Switch>

</Switch>
</Router>
</div>
)
}

Now import this two component in your App.js file also add a props element path into each route Add an extra props in home route as exact.

function App() {
return (
<div>
<Router>
<Switch>
<Route exact path="/">
<Home></Home> </Route>
<Route path="/about">
<About></About>
</Route>
</Switch>
</Router>
</div>
)
}

404:Error Route:

If you want to declare a not found route the define path as (*).You have declare as your last route.otherwise below this route wouldn’t work properly.

           <Switch>                <Route path="*">
<NotFound></NotFound>
</Route>
</Switch>

Now add a Link for each component in the app and use to="URL" to link them.

function Navbar() {
return (
<div>
<Link to="/">Home </Link>
<Link to="/about">About Us </Link>
</div>
);
};

This navbar is now linked with two router route.

Conclusion:

So that’s all for today.Happy coding. Allah Hafez.

--

--

No responses yet