A Super Short BASIC Guide on Implementing Browser Router in your React Application
React Router 6 that is!
Play this article
Table of contents
- 1. First Install react-router-dom
- 2. Import the necessary modules
- 3. Wrap every component that needs routing in a single Router component
- 4. Now Wrap them in a single Routes component
- 5. For each specific route, create a Route component inside the Routes component
- 6. For each Route component, add an element attribute and move the components into the attribute
1. First Install react-router-dom
npm i react-router-dom
2. Import the necessary modules
//App.js
import { Routes, Route, BrowserRouter as Router } from 'react-router-dom';
3. Wrap every component that needs routing in a single Router component
//... Main App
return (
<Router>
<MyComponentA />
<MyComponentB />
<MyComponentC />
</Router>
);
4. Now Wrap them in a single Routes component
return (
<Router>
<Routes>
<MyComponentA />
<MyComponentB />
<MyComponentC />
</Routes>
</Router>
);
5. For each specific route, create a Route
component inside the Routes
component
return (
<Router>
<Routes>
<Route exact path="/AandB" />
<Route path="/C" />
<MyComponentA />
<MyComponentB />
<MyComponentC />
</Routes>
</Router>
);
6. For each Route
component, add an element
attribute and move the components into the attribute
Take Note this is written in JSX so for multiple components, you will need a parent element or fragment
return (
<Router>
<Routes>
<Route
exact
path="/AandB"
element={
<>
<MyComponentA />
<MyComponentB />
</>
}
/>
<Route path="/C" element={<MyComponentC />} />
</Routes>
</Router>
);