0

I have a problem with <Redirect /> from react-router-dom. It does not redirect the user to the given path.

    const getCourse = () => {
            console.log('gg');
            <Redirect to={"/courses/" + id} /> //
        }
...
    <div className="menu__course" onClick={() => getCourse()}>

In console I see 'gg' so function is called but my path doesn't change

Monoxyd
  • 406
  • 1
  • 7
  • 18

3 Answers3

2

The <Redirect /> needs to be returned by the outer function (i.e.: the react component)

Instead, your getCourse callback should setButtonClicked(true) and you should do something like:

if (buttonClicked) {
    return <Redirect to... />
}
Bobby Connolly
  • 317
  • 2
  • 9
0

The Redirect component works when it's mounted to the virtual dom. You can't call it from a function. The following question and answer go in depth on how to solve your problem

Programmatically navigate using react router V4

Dobrin Tinchev
  • 383
  • 3
  • 10
0

You could refer to something like this

        const [course, setCourse] = useState()     

        const getCourse = () => {
            console.log('gg');
            setCourse("gg")
        }

        if(course === "gg") return <Redirect to={"/courses/" + id} />




    return <div className="menu__course" onClick={() => getCourse()}>

or if u wish to redirect from func itself use

        const getCourse = () => {
            console.log('gg');
            history.push(your-route)
        }
Vivek
  • 176
  • 1
  • 8