5

When I use react router with Redirect, Link or NavLink eveything is fine. But I need a function that navigates me to a route programmatically.

That is what I want :

if(a == 1){
    this.context.history.push("/")
}
else {
    this.context.history.push("/home");
}

As you see context history is not exists in react router v4 any more. I cannot write withroute in js code for navigation. Can anyone say me how to navigate directly in js code?

Thanks

3
  • Did you try using React Router's browserHistory ? Commented Apr 29, 2017 at 13:05
  • I am using react-router-dom i mean v4. I cannot ser any solution with it Commented Apr 29, 2017 at 22:29
  • 1
    Does this answer your question? Programmatically navigate using React router Commented Apr 30, 2021 at 15:24

1 Answer 1

9

The router will add a history to your props, you can use it like this:

this.props.history.push('/mypath')

Check this for more info: Navigating Programatically in React-Router v4

Sign up to request clarification or add additional context in comments.

1 Comment

This only changes the URL, without really navigating

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.