I'm using react-router-dom
v4.3.1
.
For example: I have the following URL
http://localhost:3000/url1/url2/url3
I need to replace only last route in URL: /url3
→ /mynewroute3
How to do it with history?
someMethod = () => {
const { history } = this.props;
history.push(`/url1/url2/url_new`); // change url3 to "url_new"
}
this.props
should have history
in it if you were using withRouter
in the root component.
When doing history.push(...)
the Router picks up the change and acts on it.
location.pathname.split('/').slice(0,-1).join('/') + '/newPath'
location.pathname.replace(/[^/]*$/, newPath)
The above takes the current window location path, cut the part after the last /
(including) and adds a new string (the new path)
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