4

I am trying to navigate programmatically using RR4. After I save some data, I then want to render a Redirect like this:

handleSave = () => {    
    this.props.mutate({
      ...
    });

    this.setState({
      org: null
    });

    <Redirect to="/orgs" />
    // return <Redirect to="/orgs" /> // Tried this also
};

I don't get an error, but the Redirect does not get rendered. If I add a switch statement in my render function, then it will work:

render() {
    return ( this.state.rerender ? <Redirect to="/orgs" push /> :
        <View>
            ...
        </View>
        )
}

This works like I want it to, but I don't like the ternary statement. Is there a way that I can add the Redirect to the save function, like I tried in my first example?

jhamm
  • 24,124
  • 39
  • 105
  • 179
  • As i noticed you have push /> in your render function which you missed in handlesave function. And one more thing is - Did you check that your handleSave() function is calling or not. – MukulSharma Sep 03 '17 at 09:37
  • `handleSave` is being called for sure. I tried with/without push. – jhamm Sep 03 '17 at 09:41

2 Answers2

1

use history prop and push or replace method. Every Route gets it, however you may also use withRouter HOC to inject it to other components.

Docs. https://reacttraining.com/react-router/web/api/history

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
1

This answer has a lot of good information and examples: https://stackoverflow.com/a/42121109/76672

Use withRouter.

This worked great for me:

import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
Jake
  • 2,058
  • 2
  • 24
  • 33