Danywalls

React Router in 3 minutes

May 05, 2019

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.

<Router>  
<div className="App container">  
<Header />  
 <My-component>  
</Router>

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.

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

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.

<p>{props.match.params.id}</p>

How to redirect to route without Link?

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

this.props.history.push(/about’)

Happy Routing.


Dany Paredes

Hi, I'm Dany Paredes, few years ago I was working with .NET, but in my last years I have been focusing in Javascript using Vue , Angular or React. You can read more in Twitter or Github.