I have a Functional Component in React in which was defined a Switch Component with some Routes. I want to pass additional props in one of these Routes (one that has parameters too), in order to use it inside the component that I will to mount when someone access the Route.
For instance, this is the Route.
<Route path="/client/:id" component={Client} />
I want to be able to pass some additional prop we need in this component. And also we need to use the Location, matches and history props inside the Client Component. For instance, we need to pass a (clientHeaderText :string)
prop.
The Client Component:
import { RouteComponentProps } from "react-router";
type TParams = { id: string };
const Client: React.SFC<RouteComponentProps<TParams>> = (props) => {
return (
<>
<h1>This is the id route parameter :{props.match.params.id}</h1>
</>
);
};
export default Client;
How can I implement this functionality?
If you need to pass additional props to a routed component then you should use the render
prop and pass through the route props and any additional props.
<Route
path="/client/:id"
render={routeProps => <Client {...routeProps} clientHeaderText="....." />}
/>
You'll likely need to add the new clientHeaderText
prop to your type definition, merged with the route props types.
If you want to pass additional Props, you can use the router custom hooks {useParams, useLocation, useHistory, useRouteMatch} in your component (You can find more about this here). With this approach, you wont need to receive the RouteComponentProps<TParams>
in your Client component and the final code looks like this.
The Route element:
<Route path="/client/:id" render={() => <Client clientHeaderText={clientHeaderText}/>}/>
The Client Component:
export type ClientProps = { clientHeaderText :string };
const Client: React.SFC<ClientProps> = (props) => {
const params = useParams<TParams>();
return (<h1> {props.clientHeaderText} : {params.id} </h1>);
};
export default Client;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With