I have the following structure for my React.js application using React Router:
JavaScript
x
25
25
1
var Dashboard = require('./Dashboard');
2
var Comments = require('./Comments');
3
4
var Index = React.createClass({
5
render: function () {
6
return (
7
<div>
8
<header>Some header</header>
9
<RouteHandler />
10
</div>
11
);
12
}
13
});
14
15
var routes = (
16
<Route path="/" handler={Index}>
17
<Route path="comments" handler={Comments}/>
18
<DefaultRoute handler={Dashboard}/>
19
</Route>
20
);
21
22
ReactRouter.run(routes, function (Handler) {
23
React.render(<Handler/>, document.body);
24
});
25
I want to pass some properties into the Comments
component.
(normally I’d do this like <Comments myprop="value" />
)
What’s the easiest and right way to do so with React Router?
Advertisement
Answer
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:
JavaScript
1
17
17
1
class Greeting extends React.Component {
2
render() {
3
const {text, match: {params}} = this.props;
4
5
const {name} = params;
6
7
return (
8
<React.Fragment>
9
<h1>Greeting page</h1>
10
<p>
11
{text} {name}
12
</p>
13
</React.Fragment>
14
);
15
}
16
}
17
Usage:
JavaScript
1
2
1
<Route path="/greeting/:name" render={(props) => <Greeting text="Hello, " {props} />} />
2
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:
JavaScript
1
33
33
1
var Dashboard = require('./Dashboard');
2
var Comments = require('./Comments');
3
4
var CommentsWrapper = React.createClass({
5
render: function () {
6
return (
7
<Comments myprop="myvalue"/>
8
);
9
}
10
});
11
12
var Index = React.createClass({
13
render: function () {
14
return (
15
<div>
16
<header>Some header</header>
17
<RouteHandler/>
18
</div>
19
);
20
}
21
});
22
23
var routes = (
24
<Route path="/" handler={Index}>
25
<Route path="comments" handler={CommentsWrapper}/>
26
<DefaultRoute handler={Dashboard}/>
27
</Route>
28
);
29
30
ReactRouter.run(routes, function (Handler) {
31
React.render(<Handler/>, document.body);
32
});
33