Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass additional props throughout a Route element that has parameters in a Typescript based React Web Application

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?

like image 660
doDDy Avatar asked Aug 20 '21 04:08

doDDy


2 Answers

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.

like image 83
Drew Reese Avatar answered Oct 14 '22 04:10

Drew Reese


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;
like image 1
Ariel Catala Valencia Avatar answered Oct 14 '22 04:10

Ariel Catala Valencia