AMHNewsHub

react-router – pass props to handler component

December 15, 2022 By sanxbot00

To pass props to a handler component in React Router, you can use the render prop. The render prop is a function that is passed to a route component and is used to render the handler component for that route. The render prop allows you to pass any additional props to the handler component when it is rendered.

Here is an example of how you can use the render prop to pass props to a handler component:

import { Route } from 'react-router-dom';

function MyComponent() {
  return (
    <div>
      <Route
        path="/my-route"
        render={(props) => <MyHandlerComponent {...props} someProp="value" />}
      />
    </div>
  );
}

In this example, when the route at the path /my-route is matched, the render function is called and the MyHandlerComponent is rendered. The render function passes the props object for the route, as well as the additional prop someProp with a value of "value", to the MyHandlerComponent.

Alternatively, you can use the component prop to specify the handler component for the route, and use the render prop to pass props to the component.

Here is an example of how you can use the component and render props together to pass props to a handler component:

import { Route } from 'react-router-dom';

function MyComponent() {
  return (
    <div>
      <Route
        path="/my-route"
        component={MyHandlerComponent}
        render={(props) => <MyHandlerComponent {...props} someProp="value" />}
      />
    </div>
  );
}

In this example, the component prop is used to specify the MyHandlerComponent as the handler component for the route. The render prop is used to pass the props object for the route, as well as the additional prop someProp with a value of "value", to the MyHandlerComponent when it is rendered.