react-router - pass props to handler component react-router - pass props to handler component javascript javascript

react-router - pass props to handler component


If you'd rather not write wrappers, I guess you could do this:

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


UPDATE

Since new release, it's possible to pass props directly via the Route component, without using a Wrapper. For example, by using render prop.

Component:

class Greeting extends React.Component {  render() {    const {text, match: {params}} = this.props;    const {name} = params;    return (      <React.Fragment>        <h1>Greeting page</h1>        <p>          {text} {name}        </p>      </React.Fragment>    );  }}

Usage:

<Route path="/greeting/:name" render={(props) => <Greeting text="Hello, " {...props} />} />

Codesandbox Example


OLD VERSION

My preferred way is wrap the Comments component and pass the wrapper as a route handler.

This is your example with changes applied:

var Dashboard = require('./Dashboard');var Comments = require('./Comments');var CommentsWrapper = React.createClass({  render: function () {    return (      <Comments myprop="myvalue"/>    );  }});var Index = React.createClass({  render: function () {    return (      <div>        <header>Some header</header>        <RouteHandler/>      </div>    );  }});var routes = (  <Route path="/" handler={Index}>    <Route path="comments" handler={CommentsWrapper}/>    <DefaultRoute handler={Dashboard}/>  </Route>);ReactRouter.run(routes, function (Handler) {  React.render(<Handler/>, document.body);});


Copying from the comments by ciantic in the accepted response:

<Route path="comments" component={() => (<Comments myProp="value" />)}/>

This is the most graceful solution in my opinion. It works. Helped me.