JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Accessing route parameters from child components in React

Author:JIYIK Last Updated:2025/03/03 Views:

React is a JavaScript library that allows you to build beautiful user interfaces for web applications. Unlike other frameworks, it does not have built-in routing capabilities, 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 basic routing utilities.

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

Components in this category are required to make everything else work properly. For example, when building a web application, you are most likely to use components react-router-domfrom the library BrowserRouter.

To perform route matching and navigation in your application, first, you have to BrowserRouterwrap it with a component. The Component BrowserRouteris usually all you need to build a web application, but it is not the only component in this category.

Check out the official documentation page for more information.

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

Typically, <Switch>there are multiple components with different paths <Route>as its children. When Switcha component finds a with a path property that matches the current URL <Route>, it renders the corresponding component and ignores all other <Route>components.

<Route>Components accept patha property where you can specify the URL structure where a particular component should be rendered. However, exactit is also important to understand the use of the property.

It is a boolean property, so you don't need to set a value. If the property is present in a component, it slightly changes the behavior of <Route>the component and pathits properties.

By default, a component will match a URL as long as the beginning of the URL follows the path Routespecified for the component path. For example, a component with this specific path will match any URL.

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

If we set exactthe prop, as in the example below, this <Route>component will try to match the entire URL, not just the beginning. Therefore, the component will only render if the URL example.com/is Home.

react-routerThe package also includes components for changing URLs. <Link>and <NavLink>are the most popular.

<Link>Is a slightly modified version of the regular link element in regular HTML <a>. It is designed for single page application libraries and frameworks.

Changing the URL using <Link>the component will not reload the page, but will change the view if necessary.

<NavLink>The component is effectively <Link>the same as , but it allows you activeto set specific styles when it is in the state (for example, when you are viewing a specific page from a menu, you can highlight that menu item).

If you are building an advanced application, you can't define separate routes for each post or even each category. Instead, you will use something called dynamic routing.

Let's look at this example.

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

This example specifies a dynamic path that is based on the idRender <Post>component. For example, the following link: example.com/posts/5will use the id=5Render <Post>component.

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

RouteOne condition for getting the path value from a component is that Routethe component should render a child component. In the above example, Postthe component is passed as childrena value, so if you try to access a dynamic parameter value, it won't work.

Instead, you can render components directly from the component using the renderor props . Let's look at both examples.componentRoute

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 componentthe property and set it to the component to be displayed when the URL matches the path.

When rendered this way, child Postcomponents still have access Routeto the components , including dynamic parameters propsin the URL .id

Alternatively, you can use the property Routeon the component renderto achieve the same result. It's a little more verbose, but may be easier to understand for some people.

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

This way, you can still access propsand props.match.params.idget idthe value from .

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

In this case, it doesn't matter whether you use the componentor renderattribute or Routepass the child component between the opening and closing tags of .

Let's look at this 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>;
}

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

It looks more readable, but useParams()hooks only work with function components.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:188 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:187 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:102 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:60 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:191 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Solve the Module not found: Can't resolve 'react-bootstrap' error

Publish Date:2025/03/16 Views:90 Category:React

To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial