0

I am attempting to redirect on clicking an item, however the redirect doesn't seem to render...

const doRedirect = () => {
    console.log('redirecting');
    return <Redirect to='/my-path' />;
}

return <div onClick={() => doRedirect()}>Click me</div>;

When I click the div, it is hittin the console log just fine, however I can't seem to get it to return the redirect...

3
  • Is there any reason why you're trying to use react router that way? I strongly suggest you take a look at useHistory hook and how you can use it to navigate between pages Commented Jul 8, 2021 at 20:21
  • <Redirect to='/my-path' /> will only work if it actually gets rendered. Commented Jul 8, 2021 at 20:21
  • You can check here on how to redirect programmatically stackoverflow.com/questions/31079081/… Commented Jul 8, 2021 at 20:23

1 Answer 1

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

const history = useHistory(); 
const doRedirect = () => {
    console.log('redirecting');
   history.push('/your-path')
}


return <div onClick={() => doRedirect()}>Click me</div>;

The way to do this is with the useHistory hook.

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

1 Comment

Ah! You are correct! I had seen things mentioned around the history and useHistory in my search, however I mistakenly thought this was a React hook like useEffect, not something witih the react-router-dom library!

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.