Accessing route parameters from child components in React
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-router
All 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-dom
from the library BrowserRouter
.
To perform route matching and navigation in your application, first, you have to BrowserRouter
wrap it with a component. The Component BrowserRouter
is 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 Switch
a 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 path
a property where you can specify the URL structure where a particular component should be rendered. However, exact
it 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 path
its properties.
By default, a component will match a URL as long as the beginning of the URL follows the path Route
specified for the component path
. For example, a component with this specific path will match any URL.
<Route path="/" component={Home}></Route>
If we set exact
the 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-router
The 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 active
to 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 id
Render <Post>
component. For example, the following link: example.com/posts/5
will use the id=5
Render <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
.
Route
One condition for getting the path value from a component is that Route
the component should render a child component. In the above example, Post
the component is passed as children
a 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 render
or props . Let's look at both examples.component
Route
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 component
the property and set it to the component to be displayed when the URL matches the path.
When rendered this way, child Post
components still have access Route
to the components , including dynamic parameters props
in the URL .id
Alternatively, you can use the property Route
on the component render
to 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 props
and props.match.params.id
get id
the value from .
Since react-router
the 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 component
or render
attribute or Route
pass 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.
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.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:172 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:153 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
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.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:78 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
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