Dawn17
Dawn17

Reputation: 8297

Redirect in react-router-dom doesn't get called

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?

Upvotes: 3

Views: 299

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104359

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 });
    }
}

Upvotes: 1

Tholle
Tholle

Reputation: 112777

<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 });
  }
}

Upvotes: 0

Related Questions