Implementing Routes with React Router DOM

Arslan Ali
3 min readMay 27, 2021

--

This entry will revolve around using a NPM Package known as React-Router-Dom, which would primarily be used in any React application of your choice.

The first step you’re going to take is installing the actual package into your application, as it is not included when using create-react-app. So you’re going to need to type npm install react-router-dom into your command line. I opted to go with this package instead of the react-router because I am not using React Native and don’t want to bog down my app with such a large package.

Next you’re going to import multiple functions from this module; BrowserRouter, Route, Switch, Link. We’ll import the first two immediately and save the other two for later, just to avoid that sometimes useful compiling warning message.

Create a function and name it routes, inside of it we will create an instance of BrowserRouter. This is the parent instance of any Router instances that go inside of it. If you are using multiple routes, then you will need to store those routes in a <div> </div>.

Route takes in two arguments; the path and the component. To keep things simple, I will create a stateless component called Homepage in this file and set it to exact path=’/’. Inside of the render, we will then set our function as the first argument of ReactDOM.

On your browser, this should render

Adding another example route requires another specific path and specific component, and you can add as many routes as you want.

On your browser, this should render on /about

But what happens when your hapless user enters the incorrect path by mistakes? Route has a way to render a component even if this mistake is made. The first argument for Routes, the exact path argument, is actually optional. All you need to do is make sure to render a default component on any path that isn’t specified by your application.

On your browser, this should render on a non-existent path;

In addition, we will be using Link to prevent page reloads when redirecting our lost user back to the homepage. To do that, just import that alongside the other and implement it onto your component, and give that Link to instance the correct route.

This is what should appear on your browser, a link to return to the homepage;

Well, that concludes my post about react-router-dom and how important it is when directing your users across your website. I hope you learned something about routes, components, and application flow.

--

--