Search code examples
reactjsurlreact-routerbrowser-history

Replace only last path part in URL


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?


Solution

  • 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)