Overview

React-router-dom is the standard library used for routing. Routing is used to change and replace components. This allows us to create single page application which allows the user to navigate to different pages without refreshing.

Installation

To install react-router to your rect application simply run the command

npm i react-router-dom

BaseRouter

The first step to use the router is to import BrowserRouter, typically renamed to Router, which encapsulates the routes.

import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import BaseRouter from './routes'; // All routes located
function App() {
return (
<div className="App">
<Router>
<BaseRouter />
</Router>
</div>
);
}
export default App;

Route

To add the routes import Route, give it a path and tell it what component should be used.

import React from 'react'
import { Route } from 'react-router-dom'
// Custom components
import ArticleList from './containers/ArticleListView';
import ArticleDetail from './containers/ArticleDetailView';
const BaseRouter = () => {
return (
<div>
<Route exact path='/' component={ArticleList} />
<Route exact path='/:articleId' component={ArticleDetail} />
</div>
)
};
export default BaseRouter;

Link

Html has its own way of routing by using <a> and href. However, using this in react would cause the application to reload. To avoid this react-router-dom has Link. To use just import and give it the path by passing it to.

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

useHistory

Sometimes you may want access to history which you can get by using useHistory

import { useHistory } from "react-router-dom";  
function Component() {
let history = useHistory();
function click() {
history.push("/home");
}
return (
<button type="button" onClick={click}>
Home
</button>
);
}

Conclusion

If you are going to create a single page application using a router is unavoidable. React-router-dom is the standard library to use and its usage is well documented and has its own guide to use. It uses dynamic routing and is highly recommended to use.

Written by

Hi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store