React allows to pass path parameters in router. It can be possible by using useParam() function which is present in 'react-router-dom' package. It can be access either in class component or function component.
Access path param in class component
In React, class components doesn't have access to useParams() Hooks from the react router dom. There are many ways to pass data down to the child component. In this example we will use wrapper function component to pass the params via the match property to a Class component. The data can also be pass to child component using Context. The params can be access in child component via props object.
Access path param in class component
1 import React from 'react';
2
3 class World extends React.Component {
4 render() {
5 return (
6 <div>
7 {}
8 Component with param <b>{this.props.match.params.username}</b> !!
9 </div>
10 );
11 }
12 }
13 export default World;
A class component does not have provision to access path parameter directly, it can be passed from parent component by using useParams() hook object that passed as property from parent component. A class component needs to be wrapped as functional component.
Access path param in function component
In React, function components have access to useParams() Hooks from the react router dom. The path parameter can be access directly using useParams() hook.
Access path param in function component
1 import React from 'react';
2
3 import { useParams } from 'react-router-dom';
4
5 function World() {
6
7 let { username } = useParams();
8 return (
9 <div>
10 {}
11 Component with param <b>{username}</b> !!
12 </div>
13 );
14 }
15 export default World;
In the above example, a function component calls useParams() hook and retrieve only one parameter from the resulting object. A username is a variable that define in the Router while registering a route in the main component.
Wrapper to access path parameter in class component
wrapper to access path parameter in class component
1 const Wrapper = (props) => {
2 const params = useParams();
3 return <World {...{ ...props, match: { params } }} />
4 }
In the above example, a Wrapper class is created using fat arrow function, it creates an params object by calling a useParams() function. A parameters of Routed component is updated using spread operator by specifying a props and additional property match by specifying a params object. It adds new property match whose value will be parameters.
Related options for your search