patternjavascriptreactCritical
react-router - pass props to handler component
Viewed 0 times
propsreacthandlerrouterpasscomponent
Problem
I have the following structure for my React.js application using React Router:
I want to pass some properties into the
(normally I'd do this like ``)
What's the easiest and right way to do so with React Router?
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var Index = React.createClass({
render: function () {
return (
Some header
);
}
});
var routes = (
);
ReactRouter.run(routes, function (Handler) {
React.render(, document.body);
});I want to pass some properties into the
Comments component. (normally I'd do this like ``)
What's the easiest and right way to do so with React Router?
Solution
UPDATE
Since new release, it's possible to pass props directly via the
Component:
Usage:
Codesandbox Example
OLD VERSION
My preferred way is wrap the
This is your example with changes applied:
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 (
Greeting page
{text} {name}
);
}
}Usage:
} />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 (
);
}
});
var Index = React.createClass({
render: function () {
return (
Some header
);
}
});
var routes = (
);
ReactRouter.run(routes, function (Handler) {
React.render(, document.body);
});Code Snippets
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>
);
}
}<Route path="/greeting/:name" render={(props) => <Greeting text="Hello, " {...props} />} />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);
});Context
Stack Overflow Q#27864720, score: 204
Revisions (0)
No revisions yet.