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.
<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 https://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.