DEV Community

Cover image for React Router Dom Tutorial
Sarah Siqueira
Sarah Siqueira

Posted on • Updated on

React Router Dom Tutorial

We are used to accessing different pages of a web application, like About, Contact, etc. To navigate on these pages we need to create routes where each route represents a different screen.

To create routes in React we can use the React Router Dom package and by the way, this is the subject of this tutorial. This package will help us to set up the routes in your app.

First of all, you need a react project. I am assuming you already have one at this point. More details about how to create a React app you can get on React's official documentation.

React Router Dom

After creating your react app using your preferred method, you need to install the react-router-dom package with the following code:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

With the project created and the react-router-dom package installed, we will create our routes file.

For this tutorial, I create my routes inside the App.js as below, but you can create a separate one, just doing the right imports later. First, I imported Routes and Route in the component.

import { Routes, Route } from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

After import, I created the routes:

//App.js

function App() {

  return (
    <Routes>
      <Route index element={<Component0 />}/>
      <Route path="/component1" element={<Component1 />}/>
      <Route path="/component2" element={<Component2 />}/>
      ...
      <Route path="/component5" element={<Component5 />}/>
      <Route path='*' element={<NotFound/>}/>
    </Routes>
  )};

export default App;
Enter fullscreen mode Exit fullscreen mode

index.js

To make sure your app will work, we need the Browser Router:

/* Browser Router from react-router-dom */
import {BrowserRouter} from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

After import you need to wrap your App with Browser Router, which I did on the index.js component:

//index.js

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>, 
    document.getElementById('root')
)

Enter fullscreen mode Exit fullscreen mode

Set links

Finally but not least important, we can create links using any component of our application, always importing the Link:

import { Link } from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

Now each link can be:

<Link to="/component1">Component1</Link>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)