dynamic pages in react-router

Dynamic Pages with React Router

By Sarah Clark
AD

Dynamic pages are a core feature of modern web applications, allowing for a seamless and engaging user experience. In the React ecosystem, routing is handled by the popular library react-router, which provides a robust and flexible solution for creating these dynamic pages. In this guide, we'll explore the ins and outs of dynamic pages using react-router, ensuring your application delightfully navigates users through various content.

React Router's primary function is to map routes to components, managing which component gets rendered based on the current URL. At its heart, it's about selecting the right path and displaying the matching view. To unleash the power of dynamic pages, we must understand how react-router manages routes and how to design our app around that.

Defining Routes with react-router

In react-router, routes are defined using the <Route> component. This component accepts several props to control the behavior of the route, with the most essential being the path prop, which specifies the URL path that activates the route.

AD
Creating a Single-Page App in React using React Router
Creating a Single-Page App in React using React Router
React Tutorial 21 - withRouter and Dynamic Routing with React Router
React Tutorial 21 - withRouter and Dynamic Routing with React Router
Master React Router: Step-by-Step Tutorial
Master React Router: Step-by-Step Tutorial

To illustrate, consider the following basic route definition:

<Route path="/users" component={Users} />

Here, react-router matches URLs starting with "/users" and renders the Users component when this route is activated.

React Router DOM ✨ #react
React Router DOM ✨ #react
Complete React.js Roadmap 2026 | Learn React Step by Step
Complete React.js Roadmap 2026 | Learn React Step by Step
Routing in React JS
Routing in React JS

Using Dynamic Segments in Routes

Dynamic segments in react-router allow us to create flexible, reusable routes. They are specified by enclosing the dynamic part incolon (:) in the path prop.

Let's dive into an example:

AD
<Route path="/users/:id" component={UserProfile} />

In this route, :id signifies a dynamic segment. When the route matches, the value of id will be available as a prop in the UserProfile component, enabling it to display dynamic content based on the URL.

10 REACT PROJECTS EVERY FRONTEND DEVELOPER SHOULD BUILD
10 REACT PROJECTS EVERY FRONTEND DEVELOPER SHOULD BUILD
React.js Roadmap for Beginners (2026 Guide)
React.js Roadmap for Beginners (2026 Guide)
an info sheet describing the different types of web pages and how they are used to create them
an info sheet describing the different types of web pages and how they are used to create them
How to Create an Editable Table Component in React
How to Create an Editable Table Component in React
Roadmap to Become a React Native Developer in 2026
Roadmap to Become a React Native Developer in 2026
a yellow background with blue text that says what is react routing?
a yellow background with blue text that says what is react routing?

In the component itself, you can access dynamic props like this:

function UserProfile({ match }) {
  const userId = match.params.id;
  // Fetch or display user data based on userId
}

Nested Routes and Layouts

react-router enables nesting routes to create complex, deeply structured apps. You can achieve this by wrapping routes inside other routes or using the <Switch> component to group related routes.

AD

For instance, consider a layout with a sidebar and a main content area:

a yellow background with the words, why use client - side routing?
a yellow background with the words, why use client - side routing?
Fun React Project Ideas for Beginners 🚀
Fun React Project Ideas for Beginners 🚀
🗺️ Create dynamic route configurations programmatically! 🤔 Which React Router hook do you use most often? Share in the comments below! 👉 Follow me for more React tips and deep dives into modern web development! _____________________________________________________ 📮 Let's connect and share React knowledge! https://shadowctrl.me ( link in bio) 🥂 Let's chill - https://discord.gg/vJ8b9AB8G2 (link in bio) ---------------------------------------------------------------------------------------... React Coding, How To Use React Router, React Hooks, React Programming, React Code, React Developer, Social Capital Network Diagram, Understanding Social Security Contributions, Understanding Social Security Rights
🗺️ Create dynamic route configurations programmatically! 🤔 Which React Router hook do you use most often? Share in the comments below! 👉 Follow me for more React tips and deep dives into modern web development! _____________________________________________________ 📮 Let's connect and share React knowledge! https://shadowctrl.me ( link in bio) 🥂 Let's chill - https://discord.gg/vJ8b9AB8G2 (link in bio) ---------------------------------------------------------------------------------------... React Coding, How To Use React Router, React Hooks, React Programming, React Code, React Developer, Social Capital Network Diagram, Understanding Social Security Contributions, Understanding Social Security Rights
function App() {
  return (
    <Router>
      <div>
        <Sidebar />
        <Switch>
          <Route path="/users" component={Users} />
          <Route path="/users/:id" component={UserProfile} />
        </Switch>
      </div>
    </Router>
  );
}

In this example, the <Switch> component ensures only one of the nested routes is rendered at a time.

Exploring Key Features of react-router

Now that we've covered the basics of dynamic pages with react-router, let's delve into some of its key features to help you create exceptional user experiences.

AD

One powerful feature is the ability to pass query parameters to components. These parameters live in the URL after a '?', allowing you to send and receive additional data. To access them, import the useLocation hook:

import { useLocation } from 'react-router-dom';

function MyComponent() {
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const value = searchParams.get('key');
  // Process the value
}

Programmatic Navigation with History

react-router offers programmatic navigation through the history object. The useHistory hook provides methods to push new routes, replace the current route, or go back in the history:

import { useHistory } from 'react-router-dom';

function MyComponent() {
  const history = useHistory();

  const goBack = () => {
    history.goBack();
  };

  const goHome = () => {
    history.push('/');
  };
}

Protecting Routes with Authentication

Implementing protected routes ensures users can only access specific pages when authenticated. You can use the <Route> component's render prop to conditionally render a component based on an authentication status:

function PrivateRoute({ component: Component, ...rest }) {
  const isAuthenticated = /* Check if user is authenticated */;

  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
}

With this understanding of dynamic pages in react-router, you're equipped to build engaging, smooth, and efficient web applications. By leveraging nested routes, dynamic segments, and crucial features like programmatic navigation, you can create an unparalleled user experience.

Embrace the power of dynamic pages in react-router to unlock a new level of flexibility and interactivity in your applications. Start designing and testing your new, enhanced user experience today!

AD