React Router in 3 minutes

Implement routing into a React app is so easy, the first step is to install react-router -dom package.

npm i react-router-dom

In the App.js import 3 essentials elements BrowserRouter, Route and Switch from react-router-dom, these handle our routes, create links and load components.

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

Every one of these components has a function in the process of add routing in our app.

The BrowserRouter is the parent component that stores all our routes and it will wrap our app in App.js.

<div className="App container">
<Header />

The Switch allows set the area to be replaced with the component when it matches with the route path.

The Route accepts the exact parameter and the path it will set the path like /about or /add and set witch component will be load.

<div className="App container">
<Header />
 <Route exact path="/" component={ContactsList} />
 <Route exact path="/add" component={Signup} />
 <Route exact path="/about" component={About} /> 

How to set NotFound Page?

Set a single route without path it will be load by default if some path doesn’t exist like http://localhost/lebroninplayoffs.

<Route component={NotFound} />

How to Link our Routes

Import and use the Link component it allows load our routes it contains a property to with your path.

import { Link } from 'react-router-dom'<Link to="/about"> About</link>

How to Passing and read parameters

To configure our route to accept params, in the route component set the path with: and the parameter name.

<Route exact path=”/about/:id” component={About} />

The params can be read throw props.


How to redirect to route without Link?

Using this.props.history.push and passing the path you can move throw routes.


Happy Routing.