Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-30 14:40:28
Original
762 people have browsed it

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>
Copy after login

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>
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template