React Router in 3 minutes

Dany Paredes
May 5 · 2 min read

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.

danywalls

My Digital life journal

Dany Paredes

Written by

A few years ago I was just a .NET guy, but in my last years I have been focusing on Front-end, building solutions with Typescript, Angular, Vue, React and Sass.

danywalls

danywalls

My Digital life journal

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade