5

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
doDDy
  • 75
  • 7

2 Answers2

3

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Yes. That's correct. I think that's the Javascript "way". But the problem with this approach is at the time of receive and use these props in the component. I mean, I really can't imagine a way to handle this props with the type definitions in the Client component. Do you have any idea of how to handle it? – doDDy Aug 20 '21 at 05:53
  • 1
    @doDDy Well, it all ends up as javascript at the end of the day. Unfortunately I'm not very versed in Typescript, though I do know enough that I believe you need a union of the route-props type and your component props type. – Drew Reese Aug 20 '21 at 06:00
1

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;