Onjsdev

Share


React Router v6 Dynamic Routing


By onjsdev

Dec 29th, 2023

In react, dynamic routing allows you to handle different routes based on dynamic parameters. In this guide, we'll walk through the basics of dynamic routing in React Router v6.

Install React Router v6

Start by installing React Router v6 in your React project using npm or yarn:

npm install react-router-dom
# or
yarn add react-router-dom

Setup Basic Routing

Before diving into dynamic routing, set up basic routing using the BrowserRouter and Routes components. Create a simple component for each route:

// App.js
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';

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

export default App;

After adding react router to your application. Let's see each step to implement dynamic routing.

Create Dynamic Routes

To handle dynamic routes, use the colon (:) syntax to specify a parameter in the route path. For example, to create a dynamic route for a user profile, you can define a route like this:

// App.js
import UserProfile from './UserProfile';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/users/:userId" element={<UserProfile />} />
      </Routes>
    </Router>
  );
}

In this example, :userId is a parameter that can be accessed in the UserProfile component.

Access Dynamic Parameters

To access dynamic parameters in your component, use the useParams hook from react-router-dom. Update your UserProfile component like this:

// UserProfile.js
import { useParams } from 'react-router-dom';

function UserProfile() {
  const { userId } = useParams();

  return (
    <div>
      <h2>User Profile</h2>
      <p>User ID: {userId}</p>
    </div>
  );
}

export default UserProfile;

Link to Dynamic Routes

When creating links to dynamic routes, use the Link component from react-router-dom:

// Home.js
import { Link } from 'react-router-dom';

function Home() {
  return (
    <div>
      <h2>Home</h2>
      <p>
        <Link to="/users/1">Visit User 1</Link>
      </p>
    </div>
  );
}

export default Home;

Clicking the "Visit User 1" link will navigate to the dynamic route /users/1.

Conclusion

Dynamic routing in React Router v6 involves creating routes with parameters and accessing those parameters in your components and showing relevant data.

By following this guide, you can implement dynamic routing in your React applications, allowing for more flexible and interactive user experiences.

Thank you for reading.