Search code examples
reactjstypescriptreact-routerreact-typescript

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?


Solution

  • 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;