DEV Community

Kyle Jung
Kyle Jung

Posted on

React Router V6 Tips+Examples

While I was working on a personal project recently using React, I realized that I could not find much up-to-date information on one of the most common things that every website would need: routing.

Here is the official documentation of React Router, but I thought I might as well provide some real-life applicated examples of the React Router and some small, useful tips.

To start off, React Router is a library that allows you to add routes to your React App. A website usually has multiple pages. For instance, let's say you're building a personal website to show off your projects. The main page would have a short introduction of yourself with some nice, professional pictures. Then you might want a separate page to put down your portfolio of your projects and work experiences. You also might want to add a contact page so that people can reach out to you.

In HTML, you would normally create a navigation bar that contains all of the links to your different pages with an <a> tag with scripts for each page. That's cool too, but in React, there is a much simpler way of organizing your routes: using the React Router.

Installation

First, install the React Router library using the following command.

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

You can always confirm your dependencies in your package.json.
Your package.json should have react-router-dom as a dependency as such.

"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0",
Enter fullscreen mode Exit fullscreen mode

Adding Routes

The next step is to add your Routes. There are multiple ways of structuring your routes. You could create a file for all of your routes, but since my application does not need a lot of routes, I opted to add my routes in my App.js.

Import BrowerRouter as the following.

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

If you have directly imported the above in your App.js as I did, wrap your app in <Router>. Then, wrap all of your Route in Routes. The following is how I did it.

function App() {
  return (
    <Router>
      <Routes>
        <Route exact path="/" element={<Home />} />
        <Route exact path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now you have two pages!

The exact prop in the <Route /> component serves to avoid confusion for the React Router. What does this mean?

Let's say you have two different routes as such without exact in neither of the routes.

<Route path="/about/1" element={<AboutMe />} />
<Route path="/about/2" element={<AboutYou />} />
Enter fullscreen mode Exit fullscreen mode

This could potentially cause partial matching problems. For example, the URL /create/user/123 will match the routes /create or /create/user/. Therefore, to avoid any room for bugs, I would suggest that you include exact in most of your routes.

The path prop specifies your route. For example, / would be equivalent to http://localhost:3000/, and /about would be equivalent to http://localhost:3000/about.

The element prop determines what to display. For me, in my / route, I wanted to display my <Home /> component and my /about route my <About /> component.

What about nested routes?
For me, I had to have different links for my posts, so I thought the structure of /posts/idNumber would be suitable for my post routes.

<Route path="/posts" element={<Post />}>
  <Route path="/posts/:postId" element={<Post />} />
</Route>
Enter fullscreen mode Exit fullscreen mode

Rather than using the self-closing tag, nest your children routes inside your parent tags.

Linking

So where does the actual linking happen?

  1. Navigate to the file that you want the actual link in.

  2. Import Link.

  3. Create the link!

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

....

<Link to={`/posts/${id}`}>See More</Link>
Enter fullscreen mode Exit fullscreen mode

The to prop is the route in this case. It serves the same purpose as ref of the <a> tag.

But what if you want to pass information to the link?

Simply create an object with the information that you want to pass to the link. Then pass the object through the state prop of <Link />
For me, I had to pass the props so this is how I did it.

const restaurantData = {
        id: id,
        name: name,
        location: location,
        zipCode: zipCode,
        coordinates: coordinates,
        phone: phone,
        price: price,
        rating: rating
}

...

<Link to={`/posts/${id}`} state={restaurantData}>See More</Link>
Enter fullscreen mode Exit fullscreen mode

That's it! One tip I would give is that plan out your routes before actually implementing your webapp. Of course you always run into situations where you have to modify your original plan, but having a general structure of your website and lining our your routes beforehand always helps.

Top comments (0)