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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 18:44:31530browse

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

Passing Props Directly

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

<Comments myprop="value" />

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" />;
  }
});

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

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

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

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!

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