1
votes

I have a ajax login in React app. It handles LoginForm component. Aplication also uses React router After ajax login I would like to make something like redirect to another React page. I dont know how to properly redirect from login page to homepage after successful login. Can somebody help me please? I am using class style to making components.

This is the code from LoginForm component:

    sendData(e)
    {
        e.preventDefault();
        this.setState({'errors': [], 'success': []});

        let formData = new FormData();
        formData.set('name', this.state.name);
        formData.set('password', this.state.password);

        axios({
            method: 'POST',
            //url: 'http://localhost:8000/login'
            data: formData,
            headers: {
                'Content-Type': 'text/html',
                'X-Requested-With': 'XMLHttpRequest',
            }
        })
            .then(response => {
               // Here should be the redirect to another React page
            })
            .catch(response => {
                this.setState({errors: ['Login fails. Try it again later please.']})
            });
    }

React Router looks like

<div className="collapse navbar-collapse" id="navbarSupportedContent">
    <ul className="navbar-nav mr-auto">
        <li className="nav-item">
            <NavLink to="/" className="nav-link">Home</NavLink>
        </li>
        <li className="nav-item">
            <NavLink to="/login" className="nav-link">Login</NavLink>
        </li>
        <li className="nav-item">
            <NavLink to="/about" className="nav-link">About</NavLink>
        </li>
    </ul>
</div>
<div className="container-fluid">
    <div>
        <Switch>
            <Route path="/" exact>
                <Home />
            </Route>
            <Route path="/login">
                <Login />
            </Route>
            <Route path="/about" component={About}/>
        </Switch>
    </div>
</div>
1

1 Answers

1
votes

If you are using functional components, you can use use useHistory hook provided by react-router-dom.

On a successful login, redirect to home page as shown below:

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

const Login = () => {
   const routerHistory = useHistory();
   ...

   const sendData = (e) => {
      ...
      .then(response => {
         // Here should be the redirect to another React page
         routerHistory.push('/');
      }) 
      ...
   }
   
   ...
}

You could also use history prop which is one of the prop passed from React Router. This will work in class based components too.

class Login {
     ...

     sendData(e) {
        ...
        .then(response => {
           // Here should be the redirect to another React page
           this.props.history.push('/');
        })
        ...
     } 

    ...
}

If Login component is not passed router props because of the hierarchy of the components in your app, then you can use withRouter higher order component to get access to history object.

import { withRouter } from "react-router";

class Login {
   ...
}

export default withRouter(Login);

For details see: