0

I am trying to redirect to the about page after successful login using React, however nothing happens even though the user successfully logs in. My Login component is shown in the code below.

import React, {useState} from 'react';
import { Auth } from 'aws-amplify';
import  { Redirect } from 'react-router-dom';

function Login(){
    // States needed to grab email and password 
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    // Once form is submitted for login call this function 
    const onSubmit = async(event) => {
        event.preventDefault();
        try{
            console.log("Submitted")
            const user = await Auth.signIn(email, password);
            return <Redirect to='/about'/>
          }catch(error){
            console.log("Error")
            console.log(error)
          }
};
  return (
      <form onSubmit={onSubmit}>
          <input value={email} onChange={event=>setEmail(event.target.value)} type="text" />
          <input value={password} onChange={event=>setPassword(event.target.value)} type="text" />
          <button>Sign Up</button>
      </form> 
      );
}

I know the code is ran because the console shows Submitted and I can access the user object. My App.js file is shown below.

import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import './App.css';


/// Components ///
import About from './components/About'
import Flower from './components/Flower'
import Home from './components/Home'
import Nav from './components/Nav'
import Login from './components/Login'

function App() {
  return (
    <Router>
      <div className="App">
        <Nav />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About}/>
          <Route path="/flower" component={Flower}/>
          <Route path="/login" component={Login}/>
        </Switch>
      </div>
    </Router>
    );
  }

export default App;

I can access all the routes by typing them into the address bar but it is just the redirect is not working. There are no errors showing either, I'd expect the browser to open the about page but nothing is showing.

Any help is appreciated!

WK123
  • 380
  • 1
  • 8

3 Answers3

1

Your login component will receive history object in props. it is made available by react-router-dom to all the routes defined inside router

function Login(props){ // receive props
    // States needed to grab email and password 
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    // Once form is submitted for login call this function 
    const onSubmit = async(event) => {
        event.preventDefault();
        try{
            console.log("Submitted")
            const user = await Auth.signIn(email, password);
            // return <Redirect to='/about'/>
            props.history.push('/about'); // use history 
          }catch(error){
            console.log("Error")
            console.log(error)
          }
};
  return (
      <form onSubmit={onSubmit}>
          <input value={email} onChange={event=>setEmail(event.target.value)} type="text" />
          <input value={password} onChange={event=>setPassword(event.target.value)} type="text" />
          <button>Sign Up</button>
      </form> 
      );
}

I hope it help

malong11
  • 558
  • 2
  • 7
  • Yep this works thanks for your help! Is there advantage to using this over states though in my answer below? – WK123 Oct 28 '20 at 17:11
  • there are both pros/cons of using history.push(). it is discussed in detail at https://stackoverflow.com/questions/46757676 – malong11 Oct 28 '20 at 17:27
1

Add a new state variable redirect.

Set redirect to be true as desired in your onSubmit() function. You'll also need to update your Login component to check if redirect is not null and redirect accordingly:

import React, {useState} from 'react';
import { Auth } from 'aws-amplify';
import  { Redirect } from 'react-router-dom';

function Login(){
    // States needed to grab email and password 
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [redirect, setRedirect] = useState(null);

    // Once form is submitted for login call this function 
    const onSubmit = async(event) => {
            // setRedirect(true) as desired
};

  if (redirect) {
    return (
      <Redirect
        to={{
          pathname: "/about",
        }}
      />
    );
  }
  return (
      <form onSubmit={onSubmit}>
          <input value={email} onChange={event=>setEmail(event.target.value)} type="text" />
          <input value={password} onChange={event=>setPassword(event.target.value)} type="text" />
          <button>Sign Up</button>
      </form> 
      );
}

Here's a Codesandbox working example.

Tejogol
  • 443
  • 5
  • 16
  • Just got pretty much exact same solution going haha great minds, do you know why I'd use this compared to the ```props.history.push``` though? – WK123 Oct 28 '20 at 17:10
  • 1
    Check this question out: https://stackoverflow.com/questions/46757676/in-react-is-it-always-better-to-render-a-redirect-than-use-this-props-history-pu – Tejogol Oct 28 '20 at 17:18
0

I got it going with using states. Think the problem I was having was that I was not returning the tag for <Redirect/> so it was not being rendered on the page. malong11 solution works too and avoids using states so it maybe the way to go but if anyone has any pros/cons welcome to hear them!


function Login(){
    // States needed to grab email and password 
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    
    // create a state for redirect and default is false 
    const [redirect_state,setredirect] = useState(false)

    // Once form is submitted for login call this function 
    const onSubmit = async(event) => {
        event.preventDefault();
        console.log("Submitted");
        try{
            console.log("Submitted")
            const user = await Auth.signIn(email, password);
            setredirect(true); // User has logged in 
          }catch(error){
            console.log("Error")
            console.log(error)
          }
};
  if (redirect_state) {
    console.log("REDIRECT EXECUTED")
    return (<Redirect to='/about'/>)
  }
  else{
    return (
        <form onSubmit={onSubmit}>
            <input value={email} onChange={event=>setEmail(event.target.value)} type="text" />
            <input value={password} onChange={event=>setPassword(event.target.value)} type="text" />
            <button>Sign Up</button>
        </form> 
        );
      }
}

export default Login;
WK123
  • 380
  • 1
  • 8