Replace only last path part in URL

Viewed 8035

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?

2 Answers

Use history.push

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.

Only change the last part of the URL;

location.pathname.split('/').slice(0,-1).join('/') + '/newPath'

Regex:

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)

I know this question is asked for React Router v4 but I was trying to perform same thing with React v5 and find this answer. For future reference, in React Router v5, I was able to perform this using the following;

history.push('./mynewroute3'); // Changes last part 

history.push ('./../mynewroute3'); // /url1/url2/url3 => /url1/mynewroute3
Related