1

Does anyone have an idea how to pass the react-router params object explicitly to a component?

I want to make something like this, because unit testing would be easier if I could pass the ApiClient from outside:

function FooComponent() {
  const apiClient = new ApiClient('http://foo.bar');
  return (
    <Bar apiClient={apiClient} param={?No idea how to pass the token param?} />
  );
}

<Router history={history}>    
  <Route path="/test" component={Test} />
    <IndexRoute component={TestIndex} />
    <Route path="/validate/:token" component={FooComponent} />
</Router>

2 Answers 2

1

If your component is attached to the route ( i.e. set as the component prop of Route as in your provided code ), it receives a prop params from react-router where you can get the route and query parameters. In your case:

function FooComponent(props) {
  const apiClient = new ApiClient('http://foo.bar');
  return (
    <Bar apiClient={apiClient} param={props.params} />
  );
}

For official example, look at : https://github.com/ReactTraining/react-router/blob/master/examples/query-params/app.js

Sign up to request clarification or add additional context in comments.

Comments

0

You can also consider something like this to pass down the router props and add some custom props to your component for example. I don't know if it is documented somewhere in react-router documentation

<Route path="/campaign/overview" component={(routeProps) =>
    <MyCoolComponent
        myCustomApiKey="secret"
        {...routeProps}
    />
}/>

You can now access this.props.params and this.props.myCustomApiKey in MyCoolComponent

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.