Home  >  Article  >  Web Front-end  >  How to Pass Custom Props to Child Components in React Router v4?

How to Pass Custom Props to Child Components in React Router v4?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 14:40:28681browse

How to Pass Custom Props to Child Components in React Router v4?

How to Pass Custom Props to Child Components in React Router v4

Problem:

In React Router v4, attempting to access route props through this.props.route returns undefined. Child components are unable to receive custom props passed from parent components.

Example Code:

<code class="javascript">// Parent Component
render() {
  return (
    <Router>
      <div>
        <Switch>
          <Route path="/" exact test="hi" component={Home} />
          <Route path="/progress" test="hi" component={Progress} />
          <Route path="/test" test="hi" component={Test} />
        </Switch>
      </div>
    </Router>
  );
}

// Child Component
render() {
  console.log(this.props); // Returns {match: {...}, location: {...}, history: {...}, staticContext: undefined}
}</code>

Solution:

To pass custom props to child components, use a render prop to define the component inline with the route:

<code class="javascript">// Parent Component
render() {
  return (
    <Router>
      <div>
        <Switch>
          <Route path="/" exact render={(props) => <Home test="hi" {...props} />} />
          <Route path="/progress" render={(props) => <Progress test="hi" {...props} />} />
          <Route path="/test" render={(props) => <Test test="hi" {...props} />} />
        </Switch>
      </div>
    </Router>
  );
}</code>

In the child component, access the custom prop as follows:

<code class="javascript">render() {
  console.log(this.props.test); // Returns "hi"
}</code>

Note: Ensure that {...props} is passed to the child component to preserve access to default router props (e.g., match, location, history).

The above is the detailed content of How to Pass Custom Props to Child Components in React Router v4?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn