How can I update a ReactJS component based on URL / path when using React-Router?
The code below works, but is this the correct way to do this? Seems like a lot of code to make a simple update. I was hoping there would be a stateful API call in the router to automatically take care of this scenario.
var MyHomeView = React.createClass({
componentDidMount: function() {
this.props.updateHeader();
},
render: function() {
return (
<div>
<h2>Home</h2>
</div>
);
}
});
var MyAboutView = React.createClass({
componentDidMount: function() {
this.props.updateHeader();
},
render: function() {
return (
<div className="my-page-text">
<h2>About</h2>
</div>
);
}
});
var MyHeader = React.createClass({
mixins: [ CurrentPath ],
getInitialState: function() {
return {
myPath: "about",
classes: "ion-ios7-information"
};
},
updateHeader: function() {
// Classnames refer to www.ionicons.com
if (this.getCurrentPath() === "/") {
this.setState( {myPath: "about" } );
this.setState( {classes: "ion-ios7-information" } );
} else {
this.setState( {myPath: "/" } );
this.setState( {classes: "ion-ios7-rewind" } );
}
},
render: function() {
return (
<Link to={this.state.myPath}>
<i className={this.state.classes} />
</Link>
);
}
});
var App = React.createClass({
updateHeader: function() {
this.refs.header.updateHeader();
},
render: function() {
return (
<div>
<MyHeader ref="header" />
<this.props.activeRouteHandler updateHeader={this.updateHeader} />
</div>
);
}
});
React.renderComponent((
<Routes>
<Route path="/" handler={App}>
<DefaultRoute handler={MyHomeView} />
<Route name="about" handler={MyAboutView} />
</Route>
</Routes>
), document.body);
Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .
A match object contains information about how a <Route path> matched the URL. match objects contain the following properties: params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path. isExact - (boolean) true if the entire URL was matched (no trailing characters)
The react-router-dom package is great for rendering different React components based on the url path. Therefore, React components can lead to others by changing the url path.
This has been updated if you are working with the react-router > v11.0.
You can read the details here
TLDR:
// v0.11.x
var Something = React.createClass({
mixins: [ Router.State ],
render: function () {
var path = this.getPath();
}
});
For the full State
API: https://github.com/rackt/react-router/blob/master/doc/04%20Mixins/State.md
In react-router 2.0.0 you can use the hashHistory or browserHistory:
browserHistory.listen(function(ev) {
console.log('listen', ev.pathname);
});
<Router history={browserHistory}>{routes}</Router>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With