Home  >  Article  >  Web Front-end  >  How to Pass Properties to Handler Components in React Router?

How to Pass Properties to Handler Components in React Router?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 17:29:02458browse

How to Pass Properties to Handler Components in React Router?

Passing Props to Handler Components in React Router

In a React application leveraging React Router, the need arises to pass properties to dynamically loaded handler components.

Consider the following React Router configuration:

<code class="javascript">var Index = React.createClass({
  render: function () {
    return (
        <div>
            <header>Some header</header>
            <RouteHandler />
        </div>
    );
  }
});

var routes = (
  <Route path="/" handler={Index}>
    <Route path="comments" handler={Comments}/>
    <DefaultRoute handler={Dashboard}/>
  </Route>
);</code>

To pass properties to the Comments component, you can extend the Index component as follows:

<code class="javascript">class Index extends React.Component { // using babel here

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <h1>
        Index - {this.props.route.foo}
      </h1>
    );
  }
}

var routes = (
  <Route path="/" foo="bar" component={Index}/>
);</code>

This approach allows you to access the foo property directly within the Index component, effectively passing it down to the Comments component.

The above is the detailed content of How to Pass Properties to Handler Components in React Router?. 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