1

I noticed that in all the examples provided by the React Router, it uses the Router objects as part of the UI that gets rendered. But I have a situation where I need to use the Redirect object outside of the rendering code. I have a set of tabs and when the user clicks on a tab, I need to redirect to a different url.

I came across one location in the Router documentation that did show how to use the Router object as part of the normal Javascript code that is not part of the rendering but I could not find it again. In essence I want to do something like this:

function doRedirect() {
    return  (<Redirect to={"/" + user.username + "/projects"} />);
}

But this will fail to compile. How can I use the Redirect functionality using the angled brackets inside of normal Javascript code?

2
  • Which version of React Router are you using? Commented Apr 10, 2020 at 8:57
  • The latest version 5.1.2 Commented Apr 10, 2020 at 9:02

1 Answer 1

2

You could use the useHistory hook, then just history.push(url) or history.replace(url) like this:

import { useHistory } from 'react-router-dom'

const MyComponent = ({ user }) => {
   const history = useHistory()

   function handleClick() {
     history.replace(`/${user.username}/projects`)
   }

   return (
     <button onClick={handleClick}>Redirect to Projects</button>
   )
}

This is just an example, but obviously you can use this with quite a lot of flexibility.

See this question for push vs replace

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

2 Comments

Does "push" do a redirect or just "push" the url onto the history stack?
It pushes it onto the history stack, but you could also use history.replace to accomplish that "redirect" functionality.

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.