Home > Web Front-end > JS Tutorial > body text

How Can I Pass Props to Handler Components in React Router?

Patricia Arquette
Release: 2024-10-23 18:44:31
Original
454 people have browsed it

How Can I Pass Props to Handler Components in React Router?

Passing Props to Handler Components in React Router

In React Router, passing props to handler components is a common requirement. Consider the following structure:

var Dashboard = require('./Dashboard');
var Comments = require('./Comments');

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>
);

ReactRouter.run(routes, function (Handler) {
  React.render(<Handler/>, document.body);
});
Copy after login

Passing Props Directly

Traditionally, you would pass props directly to the Comments component like this:

<Comments myprop="value" />
Copy after login

Passing Props via React Router

However, in React Router, props must be passed through the Route's component prop. There are two ways to do this:

1. Using a Wrapper Component

Create a wrapper component that wraps around the handler component:

var RoutedComments = React.createClass({
  render: function () {
    return <Comments {...this.props} myprop="value" />;
  }
});
Copy after login

Then, use the RoutedComments component instead of the Comments component in the route:

<Route path="comments" handler={RoutedComments}/>
Copy after login

2. Using Class Components with Route Properties

Define a class component that extends from React.Component and use the component prop:

class Index extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <h1>
        Index - {this.props.route.foo}
      </h1>
    );
  }
}

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

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

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!