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...

physicsboy
  • 5,656
  • 17
  • 70
  • 119
  • Is there any reason why you're trying to use react router that way? I strongly suggest you take a look at [useHistory](https://reactrouter.com/web/api/Hooks/usehistory) hook and how you can use it to navigate between pages – Luka Jul 08 '21 at 20:21
  • `` will only work if it actually gets _rendered_. – jonrsharpe Jul 08 '21 at 20:21
  • You can check here on how to redirect programmatically https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router – Anish Antony Jul 08 '21 at 20:23

1 Answers1

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.

Kevin.a
  • 4,094
  • 8
  • 46
  • 82
  • 1
    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! – physicsboy Jul 08 '21 at 20:27