user17893436
user17893436

Reputation: 71

React router dom v5, Redirect to another URL onClick

I am using React Router Dom v5, And, I wanted to navigate from url of localhost:3000/v3/cars to localhost:3000/cars onClick. histiry.push() adds at the end of current url, but doesn't change it/override it. For example: history.push('edit') will change the url to "localhost:3000/v3/cars/edit" and not "localhost:3000/v3/edit" How can I navigate to a different path?

Upvotes: 1

Views: 2915

Answers (2)

Mohamed Salah
Mohamed Salah

Reputation: 299

In React router dom v5 you will need to use <Redirect/>, it could be something like this

function Register () {
  const [toDashboard, setToDashboard] = React.useState(false)

  if (toDashboard === true) {
    return <Navigate to='/dashboard'/>
  }

  return (
    <div>
      <h1>Register</h1>
      <Form afterSubmit={() => setToDashboard(true)} />
    </div>
  )
}

Check the docs on react router dom v5 about Redirect here

But I recommend using React router v6 anyways, Its easier with the useNavigate, check docs here

Upvotes: 1

Karthikeyan
Karthikeyan

Reputation: 321

Using React Router DOM 5.2.1, to navigate one level up '../' can be used.

history.push({
   pathname: '../cars'
});

This will help to navigate one level up to /v3/cars and replace with /cars.

Upvotes: 1

Related Questions