login problem and onSubmit problem in react js - reactjs

I have a problem with login ( i need to check email and pass ) its only check email
my second problem is with onSubmit in form doesn't work!
`import React, {useEffect, useState} from 'react';
import loginImg from '../../assets/images/login.svg';
import {Link} from "react-router-dom";
const Login = () => {
const [email,setEmail] = useState("");
const [password,setPassword] = useState("");
const [isLogin,setIsLogin]=useState(1);
const TOKEN_KEY = 'jwt';
const handleLogin=()=>{
if (email === "bardia#test.com" && password === "1212"){
setIsLogin(1);
} else {
setIsLogin(0)
}
}
useEffect(()=>{
if (isLogin === 1){
localStorage.setItem(TOKEN_KEY, 'TestLogin');
} else {
localStorage.removeItem(TOKEN_KEY);
}
})
return (
<div className="container-fluid">
<form onSubmit={handleLogin} className="row">
<div className="col-md-6 col-sm-12 text-center align-self-center">
<div>
<p className="h1">ورود</p>
<div className="col-sm-12 col-md-4 py-4 mx-auto">
<input className="form-control" required autoFocus type="email" onChange={e => setEmail(e.target.value)} placeholder=" ایمیل خود را وارد کنید"/>
</div>
<div className="col-sm-12 col-md-4 pb-4 mx-auto">
<input className="form-control" required type="password" onChange={e => setPassword(e.target.value)} placeholder=" رمز عبور خود را وارد کنید"/>
</div>
<Link to="/dashboard" className="btn btn-primary" > ورود</Link>
</div>
</div>
<div className="col-md-6 col-sm-12">
<img src={loginImg}/>
</div>
</form>
</div>
);
};`

I hope you are doing well,In you code, Login component not triggered handleLogin method because of you don't written button type of submit. That reason not call handleLogin method in login component. so you can replace to button type submit.
syntax:
<input type="submit" value="Login">
I hope you are understand after this read.

Related

How to Redirect a Register Page to another Page using React & Formik

The page is not responding after clicking the sign up button, I wonder what went wrong with the code. I want it to redirect to "dashboards/elearning" page. The NavLink points not to the Sign Up button, and if I add a NavLink around sign up button, the validation would be pointless.
Below is the register.js file.
import React from 'react';
import { NavLink } from 'react-router-dom';
import { Button, Form } from 'react-bootstrap';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import LayoutFullpage from 'layout/LayoutFullpage';
import CsLineIcons from 'cs-line-icons/CsLineIcons';
import HtmlHead from 'components/html-head/HtmlHead';
const Register = () => {
const title = 'Register';
const description = 'Register Page';
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
email: Yup.string().email().required('Email is required'),
password: Yup.string().min(6, 'Must be at least 6 chars!').required('Password is required'),
terms: Yup.bool().required().oneOf([true], 'Terms must be accepted'),
});
const initialValues = { name: '', email: '', password: '', terms: false };
const onSubmit = (values) => console.log('submit form', values);
const formik = useFormik({ initialValues, validationSchema, onSubmit });
const { handleSubmit, handleChange, values, touched, errors } = formik;
const leftSide = (
<div className="min-h-100 d-flex align-items-center">
<div className="w-100 w-lg-75 w-xxl-50">
<div>
<div className="mb-5">
<h1 className="display-3 text-white">Multiple Niches</h1>
<h1 className="display-3 text-white">Ready for Your Project</h1>
</div>
<p className="h6 text-white lh-1-5 mb-5">
Dynamically target high-payoff intellectual capital for customized technologies. Objectively integrate emerging core competencies before
process-centric communities...
</p>
<div className="mb-5">
<Button size="lg" variant="outline-white" href="/">
Learn More
</Button>
</div>
</div>
</div>
</div>
);
// if <NavLink to="/dashboards/elearning"> Sign up </NavLink>, all other validation mathods invalid
const rightSide = (
<div className="sw-lg-70 min-h-100 bg-foreground d-flex justify-content-center align-items-center shadow-deep py-5 full-page-content-right-border">
<div className="sw-lg-50 px-5">
<div className="sh-11">
<NavLink to="/dashboards/elearning">
<div className="logo-default" />
</NavLink>
</div>
<div className="mb-5">
<h2 className="cta-1 mb-0 text-primary">Welcome,</h2>
<h2 className="cta-1 text-primary">let's get the ball rolling!</h2>
</div>
<div className="mb-5">
<p className="h6">Please use the form to register.</p>
<p className="h6">
If you are a member, please <NavLink to="/login">login</NavLink>.
</p>
</div>
<div>
<form id="registerForm" className="tooltip-end-bottom" onSubmit={handleSubmit}>
<div className="mb-3 filled form-group tooltip-end-top">
<CsLineIcons icon="user" />
<Form.Control type="text" name="name" placeholder="Name" value={values.name} onChange={handleChange} />
{errors.name && touched.name && <div className="d-block invalid-tooltip">{errors.name}</div>}
</div>
<div className="mb-3 filled form-group tooltip-end-top">
<CsLineIcons icon="email" />
<Form.Control type="text" name="email" placeholder="Email" value={values.email} onChange={handleChange} />
{errors.email && touched.email && <div className="d-block invalid-tooltip">{errors.email}</div>}
</div>
<div className="mb-3 filled form-group tooltip-end-top">
<CsLineIcons icon="lock-off" />
<Form.Control type="password" name="password" onChange={handleChange} value={values.password} placeholder="Password" />
{errors.password && touched.password && <div className="d-block invalid-tooltip">{errors.password}</div>}
</div>
<div className="mb-3 position-relative form-group">
<div className="form-check">
<input type="checkbox" className="form-check-input" name="terms" onChange={handleChange} value={values.terms} />
<label className="form-check-label">
I have read and accept the{' '}
<NavLink to="/dashboards/elearning" target="_blank">
terms and conditions.
</NavLink>
</label>
{errors.terms && touched.terms && <div className="d-block invalid-tooltip">{errors.terms}</div>}
</div>
</div>
<Button size="lg" type="submit">
Signup
</Button>
</form>
</div>
</div>
</div>
);
return (
<>
<HtmlHead title={title} description={description} />
<LayoutFullpage left={leftSide} right={rightSide} />
</>
);
};
export default Register;
You can use the useNavigate hook from react-router-dom
Please find the necessary snippet below.
import { useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
const onSubmit = (values) => {
console.log('submit form', values);
navigate('dashboards/elearning');
};
...

which condition can we add to check if user is already registered or not in react js and mysql?

import axios from 'axios';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function Register() {
const nevigate = useNavigate();
const AddUser = () => {
axios.post('http://localhost:3001/create', { name: name, email: email, contact: contact }).then((response) => {
console.log(response);
})
}
const getUser = async () => {
const response = await axios.get('http://localhost:3001/users')
console.log(response.data);
}
console.log(getUser());
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [contact, setContact] = useState();
return (
<div classNameName="App">
<section className="vh-100 bg-image"
style={{ backgroundImage: "url('https://mdbcdn.b-cdn.net/img/Photos/new-templates/search-box/img4.webp')" }}>
<div className="mask d-flex align-items-center h-100 gradient-custom-3">
<div className="container h-100">
<div className="row d-flex justify-content-center align-items-center h-100">
<div className="col-12 col-md-9 col-lg-7 col-xl-6">
<div className="card" style={{ borderRadius: "15px", overflow: 'hidden' }}>
<div className="card-body p-5">
<h2 className="text-uppercase text-center mb-5">Register Yourself</h2>
<form onSubmit={AddUser}>
<div className="form-outline mb-4">
<label className="form-label" for="form3Example1cg">Your Name</label>
<input type="text" id="form3Example1cg" className="form-control form-control-lg"
onChange={event => {
setName(event.target.value);
}} />
</div>
<div className="form-outline mb-4">
<label className="form-label" for="form3Example3cg">Your Email</label>
<input type="email" id="form3Example3cg" className="form-control form-control-lg"
onChange={event => {
setEmail(event.target.value);
}}
/>
</div>
<div className="form-outline mb-4">
<label className="form-label" for="form3Example3cg">Your contact number</label>
<input type="number" id="form3Example3cg" className="form-control form-control-lg"
onChange={event => {
setContact(event.target.value);
}}
/>
</div>
<div className="d-flex justify-content-center">
<button type="button"
className="btn btn-success btn-block btn-lg gradient-custom-4 text-body" onClick={() => nevigate('/ImgCards')}>Register</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
export default Register;
This is registration form and i am using this form when user clicks on image. after registering when user clicks on image after redirecting on page it is again asking for the registration.
How can I solve this error?

ReactJs authentication problem with empty labels

Hello im trying to learn a login system and i cannot find information on internet or i just dont know there is a information about that so problem is that when i try to login example with good registered account its fine work also when i type random words i get message that i try to login with wrong user account but when i do not write anything just leaving empty inputs i get to login so what do i need to write in code that this way wont goes in ? code below
Login.js
import React, { useState } from 'react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [msg, setMsg] = useState('');
const navigate = useNavigate();
const Auth = async (e) => {
e.preventDefault();
try {
await axios.post('http://localhost:5000/login', {
email: email,
password: password
});
navigate("/dashboard");
} catch (error) {
if (error.response) {
setMsg(error.response.data.msg);
}
}
}
return (
<section className="hero has-background-grey-light is-fullheight is-fullwidth">
<div className="hero-body">
<div className="container">
<div className="columns is-centered">
<div className="column is-4-desktop">
<form onSubmit={Auth} className="box">
<p className="has-text-centered">{msg}</p>
<div className="field mt-5">
<label className="label">Email or Username</label>
<div className="controls">
<input type="text" className="input" placeholder="Username" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Password</label>
<div className="controls">
<input type="password" className="input" placeholder="******" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<button className="button is-success is-fullwidth">Login</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
)
}
export default Login
Register.js
import React, { useState } from 'react'
import axios from "axios";
import { useNavigate } from "react-router-dom";
const Register = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confPassword, setConfPassword] = useState('');
const [msg, setMsg] = useState('');
const navigate = useNavigate();
const Register = async (e) => {
e.preventDefault();
try {
await axios.post('http://localhost:5000/users', {
name: name,
email: email,
password: password,
confPassword: confPassword
});
navigate("/");
} catch (error) {
if (error.response) {
setMsg(error.response.data.msg);
}
}
}
return (
<section className="hero has-background-grey-light is-fullheight is-fullwidth">
<div className="hero-body">
<div className="container">
<div className="columns is-centered">
<div className="column is-4-desktop">
<form onSubmit={Register} className="box">
<p className="has-text-centered">{msg}</p>
<div className="field mt-5">
<label className="label">Name</label>
<div className="controls">
<input type="text" className="input" placeholder="Name"
value={name} onChange={(e) => setName(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Email</label>
<div className="controls">
<input type="text" className="input" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Password</label>
<div className="controls">
<input type="password" className="input" placeholder="******" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Confirm Password</label>
<div className="controls">
<input type="password" className="input" placeholder="******" value={confPassword} onChange={(e) => setConfPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<button className="button is-success is-fullwidth">Register</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
)
}
export default Register

Problems with react for animation

i have the login page without the js animation
after i add the animation code i dont get a render in the login page,
i use this to add the annimation
const signUpButton = document.getElementById('signUp')
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});
signInButton.addEventListener('click', () => {
container.classList.remove("right-panel-active");
});
Here's the code:
import React from 'react';
const Loginpart = () => {
return (
<div>
<section className="position-relative pb-0">
<div className="gen-login-page-background" ></div>
<div className="container" id="container">
<div className="form-container sign-up-container">
<form action="#">
<h1 >Create Account</h1>
<span>or use your email for registration</span>
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
<button>Sign Up</button>
</form>
</div>
<div className="form-container sign-in-container">
<form action="#">
<h1 >Sign in</h1>
<span>or use your account</span>
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
Forgot your password?
<button>Sign In</button>
</form>
</div>
<div className="overlay-container">
<div className="overlay">
<div className="overlay-panel overlay-left">
<h1>Welcome Back!</h1>
<p>To keep connected with us please login with your personal info</p>
<button className="ghost" id="signIn">Sign In</button>
</div>
<div className="overlay-panel overlay-right">
<h1>Hello, Friend!</h1>
<p>Enter your personal details and start journey with us</p>
<button className="ghost" id="signUp">Sign Up</button>
</div>
</div>
</div>
</div>
</section>
</div>
);
};
export default Loginpart;
this is the code for animation :
const signUpButton = document.getElementById('signUp')
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});
signInButton.addEventListener('click', () => {
container.classList.remove("right-panel-active");
});
Chances are, when you start the handler functions, the Loginpart component still hasn't rendered.
Check the constants if they are undefined.
Perhaps this approach is more suitable for you with react
import React, {useState} from 'react'
const Component=()=>{
const [anime, setAnime] = useState(false)
function handleAnimation(){
setAnime(!anime)
}
<div id='container' className={`container ${anime&&'right-panel-active'}`}>
<button onClick={handleAnimation}></button>
</div>
}
export default Component
There are actually several ways to do this, css-in-js, or even with pure javascript, but you would have to ensure that the component is already assembled.

A component is changing controlled i/p to be uncontrolled. This is caused by value changing from defined to undefined Decide between using controlled/

this is my login.js
import React, { useState } from "react";
// import { BrowserRouter as Router, Route } from "react-router-dom";
import axios from "axios";
import { Redirect } from "react-router-dom";
import Footer from "./Bottom";
// import { FaUser, FaUnlock } from "react-icons/fa";
const Login = () => {
//functional component
const [login, setLogin] = useState({ username: "", password: "" });
// const [isSignUp, setisSignUp] = useState("");
let user;
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setLogin({ ...Login, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault(); //reload the page
if (login.username && login.password) {
axios
.post("http://localhost:8080/api/registration/login", {
username: login.username,
password: login.password,
})
.then((response) => {
sessionStorage.setItem("user", JSON.stringify(response.data));
user = response.data;
console.log(user + "**********************");
var usertype = response.data.usertype;
console.log(usertype + "////////////");
console.log(user + "*********");
if (usertype === 1) return <Redirect to="/profile" />;
// window.location.href = "http://localhost:3000/profile";
// console.log("Seller");
else if (usertype === 0) return <Redirect to="/buyerprofile" />;
// window.location.href = "http://localhost:3000/buyerprofile";
// console.log("Buyer");
})
.catch((error) => {
console.log(error.response);
});
setLogin({ username: "", password: "" });
}
};
return (
<>
<head>
<link
rel="stylesheet"
href="font-awesome-4.7.0\css\font-awesome.min.css"
/>
</head>
<section className="vh-100">
<div className="container h-100">
<div className="row d-flex justify-content-center align-items-center h-100">
<div className="col-lg-8 col-xl-9">
<div className="card text-black" style={{ borderRadius: "25px" }}>
<div className="card-body p-md-5">
<div className="row justify-content-center">
<div className="col-md-10 col-lg-6 col-xl-7 order-2 order-lg-1">
<p className="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">
Login
</p>
<form onSubmit={handleChange} className="mx-1 mx-md-4">
<div className="d-flex flex-row align-items-center mb-4">
<i
class="fa fa-user-circle fa-lg"
aria-hidden="true"
></i>
<div className="form-outline flex-fill mb-0">
<input
type="text"
id="username"
name="username"
className="form-control"
placeholder="User Name"
value={login.username}
onChange={handleChange}
/>
{/* {errors.username &&<p className="error">{errors.username}</p>} */}
</div>
</div>
<div className="d-flex flex-row align-items-center mb-4">
<i class="fa fa-unlock fa-lg" aria-hidden="true"></i>{" "}
<div className="form-outline flex-fill mb-0">
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Password"
value={login.password}
onChange={handleChange}
/>
{/* {errors.password &&<p className="error">{errors.password}</p>} */}
</div>
</div>
<div className="d-flex justify-content-center mx-4 mb-3 mb-lg-4">
<button
type="submit"
className="btn btn-primary btn-lg"
onClick={handleSubmit}
>
Login
</button>
</div>
</form>
</div>
<div className="col-md-10 col-lg-6 col-xl-5 d-flex align-items-center order-1 order-lg-2">
<img/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<Footer />
</>
);
};
export default Login;
& if I try to login with my credentials it throws this error in console & this warning shows as soon as I start typing in input field
Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. at input
at div
at div
at form
at div
at div
at div
at div
at div
at div
at div
at section
at Login
I am new to react & I was trying my hands with react+sprinboot project, I saw some answers on uncontrolled input to controlled but here it's in-> reverse controlled input to uncontrolled,so what exactly is the difference?
Inside the handleChange function:
setLogin({ ...Login, [name]: value });
i think you meant to write "login" and not "Login", the warning may be caused by that.

Resources