Johann
Johann

Reputation: 29867

Using React Router functionality outside the rendering

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?

Upvotes: 1

Views: 33

Answers (1)

Barry Michael Doyle
Barry Michael Doyle

Reputation: 10598

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

Upvotes: 2

Related Questions