3
handleLogin() {
  const { username, password } = this.state;
  if (username === 'test' && password === '1234') {
    this.setState({ error: false });
    auth.authenticate();
    alert('done')
    return <Redirect to="/"/>
  } else {
    this.setState({ error: true });
  }
}

This function is an onClick handler for my buttong. Whenever I type in the right id and pw, I intend to redirect the user to the "/" route. The alert gets called but it doesn't get redirected to the path. Is this the right usage?

Tholle
  • 108,070
  • 19
  • 198
  • 189
Dawn17
  • 7,825
  • 16
  • 57
  • 118
  • 4
    `` is a component you need to render in a component's `render` method for it to redirect. You can use `this.props.history.push` or `this.props.history.replace` instead if your want to redirect programmatically. – Tholle Jul 19 '18 at 18:10
  • 1
    @Tholle That's exactly what I wanted! Thanks. – Dawn17 Jul 19 '18 at 18:12

2 Answers2

1

Redirect is a ui element, and handleLogin is a event handler, it will not render the element. To navigate dynamically you need to push a new entry into history.

If you are rendering that component in some route then, use this.props.history.push. If the component is child of some other component then use withRouter to get the access of history object first then do the history.push.

Check this answer: Programmatically navigating in React-Router v4

Like this:

handleLogin() {
    const { username, password } = this.state;
    if (username === 'test' && password === '1234') {
        this.setState({ error: false });
        auth.authenticate();
        alert('done')

        this.props.history.push('/');

    } else {
        this.setState({ error: true });
    }
}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
0

<Redirect /> is a component you need to render in a component's render method for it to redirect. You can use history.push or history.replace instead if your want to redirect programmatically.

If the component is not used directly in a Route, you can use the withRouter HOC to get access to the history object in the props.

handleLogin() {
  const { username, password } = this.state;
  if (username === 'test' && password === '1234') {
    this.setState({ error: false });
    auth.authenticate();
    alert('done')
    this.props.history.push('/');
  } else {
    this.setState({ error: true });
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189