How to implement React Routes

Daniel Cooper
2 min readDec 21, 2020

As the title suggests this blog will be and guide on how to implement routes in react. With that said let us get into the guide.

Step One

Step one is to install react-router-dom. If you already have react-router-dom installed you can skip down to step two.

To install react-router-dom you can copy the following line of code into your terminal :

npm i react-router-dom

Step Two

Step two is to create your components and set up your app component I’ll leave some examples down below :

Home component

Import React from “react”;function Home() {
Return <h2>home</h2>;
}
export default Home;

About component

Import React from “react”;function About() {
Return <h2>About</h2>;
}
export default About;

App component

import React from "react";
import Home from "path"
import Aboutfrom "path"
function App(){
return (
<div>
<nav>
<ul>
<li>Home</li>
<li>About</li>
</ul>
</nav>
</div>
);
}

Step Three

Now that we have our componets ready to go the next step is to hook them up to routes. In the App component we are going to start off by importing a few things. Switch, Route, Link, and BrowserRouter but we are going to add “as Router” to change the prefix.

We are going to use Link to link our list items to specific paths. Like how Home is linked to “/”. Route is used to associate a component to render with a path. Switch will render the first child route with a matching path. BrowserRouters job is to keep the UI in sync with the URL.

import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Home from "path"
import Aboutfrom "path"
function App(){
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}

Now that our app has routes clicking on one of those list items will render the corresponding component. This is a quick way to get started with routes and they can get way more complicated. This blog is meant to help you understand how to implement routes and help you gain an understanding of how they work. As always links I found useful while writhing this well be linked below. I hope this blog was helpful to you in any way.

Helpful links

--

--