React Router v6 – A Simple Introductory Guide

1. Setting Up Your React Project

If you haven’t already, set up your React app using Create React App:

npx create-react-app my-app
cd my-app

Once the app is ready, install React Router:

npm install react-router-dom@6

2. Setting Up Routing

Create Your Page Components

For simplicity, let’s create 3 components for our app: Home, About, and Contact.

import React from "react";

function Home() {
  return <h1>Welcome to the Home Page!</h1>;
}

export default Home;
import React from "react";

function About() {
  return <h1>Learn more About Us!</h1>;
}

export default About;
import React from "react";

function Contact() {
  return <h1>Contact Us!</h1>;
}

export default Contact;

Configuring React Router in App.js

Now, let’s set up the routes in the App.js file. React Router v6 introduces the Routes component, replacing the Switch component from v5, and you define the route paths using the Route component.

import React from "react";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>

        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </div>
    </Router>
  );
}

export default App;

Explanation:

  • <BrowserRouter as Router>: This is the router wrapper that keeps track of the current location (URL). It’s required to use React Router in the app.
  • <Link>: This replaces the traditional anchor tag <a>. It allows for navigation without a full page reload, which is key to making a React app behave like a single-page application (SPA).
  • <Routes>: This component contains all your Route definitions. In v6, we replaced Switch with Routes, and it automatically chooses the best match for the route.
  • <Route>: Each Route defines a path and the corresponding component (element) to render when that path is matched. We no longer need to pass component props in React Router v6; instead, we pass JSX directly via the element prop.

3. Running Your App

Now you can start your app:

npm start

Go to http://localhost:3000/ in your browser, and you should see your app. The navigation should work seamlessly when you click the links (Home, About, Contact) and switch between the pages.


4. Additional Notes on React Router v6 Features

Here are some important features and changes introduced in React Router v6:

  • No more exact prop: In v6, routes are always exact by default, meaning the path has to match exactly. You no longer need to specify exact like you did in v5.
  • Nested Routes: You can easily nest routes within routes. For example, if you wanted to have a Dashboard component with nested Profile and Settings pages, React Router v6 makes this simpler.

Example of nested routes:

<Routes>
  <Route path="/dashboard" element={<Dashboard />}>
    <Route path="profile" element={<Profile />} />
    <Route path="settings" element={<Settings />} />
  </Route>
</Routes>

useNavigate Hook: React Router v6 also introduces the useNavigate hook, which you can use to programmatically navigate between pages. This replaces the history.push method from v5.

Example:

import { useNavigate } from "react-router-dom";

function Home() {
  const navigate = useNavigate();

  const goToContact = () => {
    navigate("/contact");
  };

  return (
    <div>
      <h1>Welcome to the Home Page!</h1>
      <button onClick={goToContact}>Go to Contact</button>
    </div>
  );
}

Conclusion

With React Router v6, navigating between pages in your React app is now simpler and more intuitive. You just need to define your routes within the Routes component and use the Link component to navigate. Additionally, hooks like useNavigate make it easier to handle programmatic navigation.

For more advanced features, check out the official documentation.


Posted

in

by

Post’s tag:

Advertisement