How to Access Route Parameters From Child Component in React

Irakli Tchigladze Feb 02, 2024
  1. Essential Components and Their Attributes in React Router
  2. How to Access Parameters From the Child Component in React
  3. Get Parameters Using the useParams() Hook in React
How to Access Route Parameters From Child Component in React

React is a JavaScript library that allows you to build beautiful user interfaces for your web applications. Unlike other frameworks, it doesn’t have built-in routing functionality, so React developers need to use external libraries.

The most popular routing library for React is react-router, which includes many custom components essential for navigation, route matching, and other essential routing utilities.

Essential Components and Their Attributes in React Router

React Router follows the component-based approach of the core React library. All the components included in the react-router package can be separated into three broad categories: routers, route matchers, and navigator components.

  1. Routers

The components in this category are necessary to make everything else work. For instance, when building web applications, you’re most likely to use the BrowserRouter component from the react-router-dom library.

To perform route matching and navigation within your application, first, you must wrap it with the BrowserRouter component. BrowserRouter is usually needed for building web applications, but it’s not the only component in this category.

Check out the official documentation page to learn more.

  1. Route Matcher Components

Two custom components, specifically <Switch> and <Route>, fall under route matchers. React developers use the two in combination to determine which component needs to be rendered based on the current URL.

Normally, the <Switch> has multiple <Route> components with different paths as its children. When the Switch component finds the <Route> with the path attribute that matches the current URL, it will render the respective component and ignore all other <Route> components.

The <Route> components accept a path attribute, where you can specify the URL structure that should render a specific component. However, it’s also important to understand the use of the exact attribute.

It’s a Boolean attribute, so you don’t need to set a value. If the attribute is present in the component, it slightly alters the behavior of the <Route> component and its path attribute.

By default, a component matches with the URL as long as the beginning of the URL follows the path specified for a Route component. For instance, the component with this specific path will match any URL.

<Route path="/" component={Home}></Route>

If we set the exact attribute, like in the example below, this <Route> component will attempt to match the entire URL, not just the beginning. So the Home component will only render if the URL is example.com/.

  1. Components For Navigation

The react-router package also includes components for changing the URL. The <Link> and <NavLink> are the most popular.

<Link> is a slightly modified version of a regular <a> link element in regular HTML. It is designed for Single Page Application libraries and frameworks.

Changing the URL using the <Link> component doesn’t reload the page but changes the view when necessary.

The <NavLink> component is practically the same as <Link>, but it allows you to set specific styles when it is in an active state (for instance, when you’re viewing a specific page from your menu, you can highlight that menu item).

How to Access Parameters From the Child Component in React

If you’re building an advanced application, you can’t define a separate route for every post or even every category. Instead, you’re going to use something called dynamic routes.

Let’s take a look at the example.

<Route path="/posts/:id">
    <Post></Post>
</Route>

This example specified a dynamic path that renders <Post> components, depending on the id. For instance, the following link: example.com/posts/5 will render the <Post> component with id=5.

But what if you need to access parameters of the dynamic path from the child component? The <Post> component might need to display its id.

One condition for getting the path value from the Route component is that the Route component should render the child component. In the above example, the Post component is passed as a children value, so if you try to access dynamic parameter values, it won’t work.

Instead, you can render the component directly from the Route component by using either the render or component attributes. Let’s look at both examples.

export default function App() {
  return (
    <BrowserRouter>
      <Route exact path="/posts/:id" component={Post}></Route>
    </BrowserRouter>
  );
}
function Post(props) {
  return <h2>ID is {props.match.params.id}</h2>;
}

In this case, we use the component attribute and set it to the component we want to display when the URL matches the path.

When rendered like this, the child Post component still has access to the props from the Route component, including the dynamic id parameter from the URL.

Look at the live CodeSandbox demo to understand better.

Alternatively, you can use the render attribute on the Route component to achieve the same result. It is slightly more verbose, but it might be easier to understand for some people.

<Route exact path="/posts/:id" render={(props) => <Post {...props}></Post>}

This way, you can still access the props and get the id value from props.match.params.id.

Get Parameters Using the useParams() Hook in React

Since the release of react-router version 5.1, the package also includes a useful useParams() hook, allowing developers to easily access the parameters from the URL.

In this case, it doesn’t matter whether you use component or render attributes or pass the child component between the opening and closing tags of Route.

Let’s look at the example.

import {useParams} from "react-router-dom"
export default function App() {
  return (
    <BrowserRouter>
      <Route exact path="/posts/:id">
          <Post></Post>
       </Route>
    </BrowserRouter>
  );
}
function Post(props) {
  let {id} = useParams()
  return <h2>ID is {id}</h2>;
}

The useParams() hook returns an object with key-value pairs of the parameters from the URL. We can destructure it when defining the variable and referencing it within JSX.

It looks much more readable, but the useParams() hook only works for functional components.

Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn

Related Article - React Router