Home > Article > Web Front-end > 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!