Node.JS
Node.JS

Reputation: 1570

React router push to history and preserve relative path

I am using react router and I have the following code:

let history = useHistory();

let goToReviewPage = () => history.push(`review/${productId}`);

My current url is: /foo/bar and calling goToReviewPage() will redirect me to

/foo/review/${productId} instead of /foo/bar/review/${productId}

I am not sure how to set the base path will pushing the history.

Upvotes: 1

Views: 5886

Answers (2)

Johnny Oshika
Johnny Oshika

Reputation: 57482

You can use React Router's match.url. Example:

const Component = ({ productId }) => {
  const match = useRouteMatch();
  const history = useHistory();

  const handleClick = () => {
    history.push(`${match.url}/review/${productId}`);
  };

  return (
    <button onClick={handleClick}>Click me</button>
  );
};

Upvotes: 7

Daniel
Daniel

Reputation: 1601

One way is to use window.location to obtain the current path.

For example:

history.push(window.location.pathname + '/' + `review/${productId}`);

window.location api

Upvotes: 1

Related Questions