How to create login and redirect to another page after success?

Viewed 216

How to create login and redirect to another page after success? i trying to below code but not working anyone can help me ? i don't know how to login and redirect to home page i am created below login page but i don't know how to check and redirect

    import React, { useState } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import { Redirect } from "react-router";
import "./Login.css";

const Login = (props) =>{

    const[redirect,setRedirect]=useState();
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState("");


    function validateForm() {
        return email.length > 0 && password.length > 0;
    }

    function handleSubmit(event) {
        event.preventDefault();
        if (!(username === '123456' && password === '123456')) {
            return setError(true);
        }
        setRedirect("/");
    }

    return(
        {redirect?<Redirect to={redirect}/>:null}
        <div className="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div className="Login">
              <Form onSubmit={handleSubmit}>
                <Form.Group size="lg" controlId="email">
                  <Form.Label>Email</Form.Label>
                  <Form.Control
                    autoFocus
                    type="text"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </Form.Group>
                <Form.Group size="lg" controlId="password">
                  <Form.Label>Password</Form.Label>
                  <Form.Control
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </Form.Group>
                <Button block size="lg" type="submit" disabled={!validateForm()}>
                  Login
                </Button>
              </Form>
            </div>
        </div>
    )
}
export default Login
2 Answers

Check below its working

LoginForm.js

import React, { useState } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import "./Login.css";

function LoginForm({Login, error}) {
    const [details, setDetails] = useState({email:"", password:""});
    const submitHandler = e =>{
        e.preventDefault();
        Login(details);
    }
    return(
        <div className="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div className="login">
                <h2 style={{textAlign:'center'}}>Login</h2>
                <Form onSubmit={submitHandler}>
                <Form.Group size="lg" controlId="email">
                  <Form.Label>Email</Form.Label>
                  <input
                    className="form-control"
                    autoFocus
                    type="email"
                    name="email"
                    id="email"
                    onChange={e => setDetails({...details, email: e.target.value})}
                    value={details.email}
                  />
                </Form.Group>
                <Form.Group size="lg" controlId="password">
                  <Form.Label>Password</Form.Label>
                  <input
                    className="form-control" 
                    type="password"
                    name="password"
                    id="password"
                    onChange={e => setDetails({...details, password: e.target.value})}
                    value={details.password}
                  />
                </Form.Group>
                <Button block size="lg" type="submit">
                  Login
                </Button>
              </Form>
            </div>
        </div>
    )
}
export default LoginForm

App.js

import React, { useState } from 'react';
import './App.css';
import LoginForm from './LoginForm';
function App() {

  const adminUser = {
    email: "admin@admin.com",
    password: "admin123"
  }

  const [user, setUser] = useState({email:""});
  const [error, setError] =useState("");

  const Login = details =>{
    console.log(details);
    if(details.email == adminUser.email && details.password == adminUser.password){
      console.log("Logged in");
      setUser({
        email:details.email
      })
    }else{
      console.log("User Password Wrong!");
    }
  }

  const Logout = () =>{
    setUser({email: ""})
  }

  return (
    <div className="App">
      {(user.email !="") ? (
        <div className="welcome">
          <h2>Welcome, <span>{user.email}</span></h2>
          <button onClick={Logout}>Logout</button>
        </div>
      ):(
        <LoginForm Login={Login} error={error} />
      )}
    </div>
  );
}

export default App;

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

You can easily approach it with window.location.href as below.

const App = (props) =>{

const[redirect,setRedirect]=useState();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");


function validateForm() {
    return email.length > 0 && password.length > 0;
}

function handleSubmit(event) {
    event.preventDefault();
    if (!(email=== '123456' && password === '123456')) {
        console.log("Error")
    }
    window.location.href = "/";

}

return(
    <div className="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <div className="Login">
          <Form onSubmit={handleSubmit}>
            <Form.Group size="lg" controlId="email">
              <Form.Label>Email</Form.Label>
              <Form.Control
                autoFocus
                type="text"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </Form.Group>
            <Form.Group size="lg" controlId="password">
              <Form.Label>Password</Form.Label>
              <Form.Control
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </Form.Group>
            <Button block size="lg" type="submit" disabled={!validateForm()}>
              Login
            </Button>
          </Form>
        </div>
    </div>
   )
}
export default App;
Related