DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Getting started with React Router!
Emmanuel Aiyenigba
Emmanuel Aiyenigba

Posted on

Getting started with React Router!

React router

What is React Router

React Router (RR) is a library that is used to create routes in your React application. Oh, no, it doesn't come pre-installed in your react project - you have to install it using npm install react-router-dom

You most likely have come across web apps that routes you to a new page depending on what action you specify and you wonder, "how do I do this in my application."

In this post you are gonna be learning how RR works and how you can use them in your project for routing.

React Router is powerful and efficient because it has features that allow you to load your code lazily, dynamic route matching, location transition building, route nesting, index routing etc.

Let's jump right in and learn how to use this powerful library.

Prerequisite

  • Node: you should have Node installed installed on your computer.

  • Have a working knowledge of React

Shall we begin?

Let's begin by creating a React app using the create-react-app CLI

npx create-react-app learn-react-router

Ensure that our React app is installed successfully.

Now let's install react-router

Do npm install react-router-dom

Yep, congratulations. You just passed the first step to working with React Router.

Now let's create a routes folder inside our src folder so that we can have our components in there.

create Users.js file and include just a simple text like this.

// => Users.js
import React from 'react'


export default function Users() {
  return (
    <div>
        <h1>Welcome to Users route </h1>

    </div>


  )
}

Enter fullscreen mode Exit fullscreen mode

Let's also create a Post.js file inside the same routes folder

// => Posts.js
import React from 'react'


export default function Posts() {
  return (
    <div>
        <h1>Welcome to Posts route</h1>

    </div>


  )
}


Enter fullscreen mode Exit fullscreen mode

Holdup! I hope your app is running, if no, get it running by doing npm start

It's time to make our routes navigable using React Router.

Go to the index.js file

// => index.js

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Users from './routes/Users';
import Posts from './routes/Posts';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />} >
         <Route path="users" element={<Users/>} />
         <Route path ="posts" element={<Posts />} />
          <Route path="*" element={<h1>Route does not 
            exist</h1>}/>
      </Routes>
  </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();



Enter fullscreen mode Exit fullscreen mode

If you navigate to localhost:3000/users you will be taken to the users page where you will find the text Welcome to Users route as we've specified the text inside Users.js. Of course you can also navigate to the posts route localhost:3000/posts.

Whoa! Whoa! Whoa! Did I just hear you say "what the fuck is BrowserRouter, Routes and Route?
I'm so sorry about that, I had absolutely no intention to annoy you - I was about to explain them.

BrowserRouter. Give me a moment, please. I need to say this:

"this is a blog post aimed at helping you understand a particular subject matter and not a documentation."
Suffice to say, I might most likely not use the vocabularies found in the documentation.

Back to the what I was about to say before the emmm...the mosquitoes interrupted...

BrowserRouter kind of announce that "yo! this person is about to create a route"
But then you can't exactly own a house in BrowserRouter (think of it has a city) without the Mayor giving you a go ahead - Routes is the Mayor. You have to put each of your Route inside it.

Route requires two parameters that you must specify:

element: this is it trying to tell you "yo! where should I drive to when I hit the road." Road here would be path. This place to drive to is usually a component.

path: this is the road that leads to your destination (a component)!

Got that? Yeahhh!

path="*" what's that?
Oh, I almost forgot that. This is called upon only when the route the user request does not exist. In this case we asked it to say "Route does not exist"

Wanna see for yourself? Okay do localhost:3000/home. What did it tell ya?
Now you get it!

Hollup instructor! How can I link to a particular route when a user clicks something?
Smart student! You simply link it (winks). Let's do that.

// => App.js

import React from 'react';
import {Link} from 'react-router-dom'

export default function App() {
  return (
    <div>


        <h1>Welcome to the HOMEPAGE</h1>


        <Link to="/users">
             <p>go to users page</p>
       </Link> 

    </div>
  )
}


Enter fullscreen mode Exit fullscreen mode

Notice that I imported something called Link from react-router-dom and I specified, using to="", where the link should go when <p>...</p> is clicked.

Test it out yourself. Yeahhhhhhhhhh! its working - I can feel your excitement from over here.

I want to keep this as basic as possible, I don't want to overload you. I want you to feel the taste of each bite.

one last thing, I promise!

Nested Routes

The official documentation has this to say of Nested routes:

" This is one of the most powerful features of React Router making it so you don't have to mess around with complicated layout code. The vast majority of your layouts are coupled to segments of the URL and React Router embraces this fully.

Routes can be nested inside one another, and their paths will nest too (child inheriting the parent). "

This is what I have to say: imagine you want to do something like this localhost:3000/users/name. Nested route helps you achieve that.

Let's go to our index.js file to do this... but before that ensure you create a Name.js file inside the routes folder. You should write a JSX inside - something like "this is the name route and it will appear inside the users (parent) route" or just anything

// => index.js

...

<Route path="users" element={<Users />} >
    <Route path="name" element={Name />} />
</Route>
...

Enter fullscreen mode Exit fullscreen mode

You simply nest the child route inside it's parent route.

To make this functional you have to import and add Outlet into the parent route.

// => Users.js
import React from 'react'
import {Outlet} from 'react-router-dom'


export default function Users() {
  return (
    <div>
        <h1>Welcome to Users route </h1>

    </div>
    <Outlet />


  )
}

Enter fullscreen mode Exit fullscreen mode

Test it out! Navigate to the name route using localhost3000/users/name

Hurrayyyyyy!

Top comments (0)

πŸ—£ Want to join the conversation?

Β 
It's easy! Become a DEV member to follow this post, comment, and more.