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
How to reverse an array in React
Publish Date:2025/03/13 Views:198 Category:React
-
在 React 中反转数组:使用扩展语法 `(...)` 创建数组的浅表副本。在副本上调用 `reverse()` 方法。将结果存储在变量中。
Setting data attributes in React
Publish Date:2025/03/13 Views:84 Category:React
-
要在 React 中为元素设置 data 属性,请直接在元素上设置属性,例如 或使用 setAttribute() 方法,例如 el.setAttribute('data-foo', 'bar')。 我们可以访问事件对象上的元素或
Toggle a class on click in React
Publish Date:2025/03/13 Views:153 Category:React
-
要在 React 中单击时切换类:在元素上设置 onClick 属性。将活动状态存储在状态变量中。使用三元运算符有条件地添加类。
Sorting an array of objects in React
Publish Date:2025/03/13 Views:77 Category:React
-
在 React 中对对象数组进行排序: 创建数组的浅拷贝。 调用数组的 `sort()` 方法,传递给它一个函数。 该函数用于定义排序顺序。
Generate a random number in React
Publish Date:2025/03/13 Views:189 Category:React
-
使用 Math.random() 函数在 React 中生成一个随机数,例如 Math.floor(Math.random() * (max - min + 1)) + min。 Math.random 函数返回 0 到小于 1 范围内的数字,但也可用于生成特定范围内的数字。
Open links in new tabs with React
Publish Date:2025/03/13 Views:76 Category:React
-
要在 React 的新选项卡中打开链接,请使用 a 元素并将其 `target` 属性设置为 _blank,例如 。 _blank 值表示资源已加载到新选
How to set target=_blank in React
Publish Date:2025/03/13 Views:199 Category:React
-
要在 React 中将元素的目标属性设置为 _blank,请使用锚元素并设置 rel 属性,例如 。 _blank 值表示资源已加载到新选项卡中。
Showing hover elements in React
Publish Date:2025/03/13 Views:177 Category:React
-
要在 React 中显示悬停元素:在元素上设置 `onMouseOver` 和 `onMouseOut` 属性。 跟踪用户是否将鼠标悬停在状态变量中的元素上。 根据状态变量有条件地渲染其他元素。
Passing components as props in React
Publish Date:2025/03/13 Views:164 Category:React
-
我们可以使用内置的 children 属性在 React 中将组件作为属性 props 传递。 我们在组件的开始标签和结束标签之间传递的所有元素都会分配给 children 属性。