ReactJs authentication problem with empty labels - reactjs

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

Related

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?

How to pass data from page to another page

Hello guys i have a react project made with react, node, express, and mysql. The thing is i want to get email from login and pass to home page. How do i do that, i dont want to use useParams() because the user can input their email in the link, i want to avoid that. Is there any way to do that and if you can, can you give code example.
Login
const Login = () => {
let navigate = useNavigate();
const [emailLog, setEmailLog] = useState("");
const [passwordLog, setPasswordLog] = useState("");
const [loginStatus, setLoginStatus] = useState("");
Axios.defaults.withCredentials = true;
const login = (e) => {
e.preventDefault()
Axios.post("http://localhost:3001/login" , {
email: emailLog,
password: passwordLog
}).then((response)=> {
console.log(response)
if(response.data.message) {
alert((response.data.message))
} else{
setLoginStatus(response.data[0].email)
alert("Redirecting")
navigate("/home")
}
})
}
useEffect(() => {
Axios.get('http://localhost:3001/login').then((response)=> {
if(response.data.loggedIn == true) {
setLoginStatus(response.data.email[0].email)
}
})
})
return (
<div>
<img className="wave" src={Wave} />
<img className="wave2" src={WaveV2} />
<div className="wrapper">
<div className="img">
{/* <img src={Background}/> */}
</div>
<div className="register-content">
<div className='registerForm'>
<img src={Avatar} />
<h2 className="title">Welcome</h2>
<div className="input-div one">
<div className="i">
<i className="fas fa-user"><GrMail /></i>
</div>
<div className="div">
<input type="email" className="input" placeholder='Email' required
onChange={(e)=> {
setEmailLog(e.target.value)
}}/>
</div>
</div>
<div className="input-div pass">
<div className="i">
<i className="fas fa-lock"><AiFillLock /></i>
</div>
<div className="div">
<input type="password" className="input" placeholder='Password' required
onChange={(e)=> {
setPasswordLog(e.target.value)
}}/>
</div>
</div>
Don't have an account ?
<button type='submit' className='btn' onClick={login} data={emailLog}>Login</button>
</div>
</div>
</div>
</div>
)
}
export default Login
App.js
function App() {
const [invoice, setInvoice] = useState("");
const [date, setDate] = useState ("");
const [currency, setCurrency] = useState ("IDR");
const [ myFile, setMyFile] = useState("");
const [test, setTest] = useState("anjay#anjay.com");
Axios.defaults.withCredentials = true;
return (
<div className="App">
<BasicExample />
<div className='formInput'>
<form method='POST' encType='multipart/form-data' action='http://localhost:3001/upload'>
<div className='textUser'>
<h1>{props.data}</h1>
</div>
<input className='inputForm' defaultValue={test} type="email" disabled name='email' />
<input className='inputForm' type="number" placeholder='Invoice No' name='InvoiceNo' />
<input className='inputForm' type="date" name='Invoice_Date' />
<input className='inputForm' type="text" placeholder='Description' name='Description' />
<select className='selectBox' name='Currency' onChange={(e)=> {
setCurrency(e.target.value);
}}>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<input className='inputForm' type="number" placeholder='Amount' name='Amount'/>
<input className='custom-file-upload' multiple type="file" name="DocumentFile" onChange={(e)=> {
setMyFile(e.target.value);
}} />
<button className='btnSubmit'>Submit</button>
</form>
</div>
</div>
);
}
export default App;
I think props drilling should solve it.
example
Login Component
function Login({email, setEmail}){
// you need to update state email here
}
Home or App.js
function App(){
const [email, setEmail] = useState("");
// here you should pass the props to login component,
// so you have the ability to set or asign the email state
<Login email={email} setEmail={setEmail} />
}
If you want to send data tp one page, you can use state with navigate.
navigate("/home", {state: { email: emailLog }})
you can get data from your home component like,
{props.location.state.email}

login problem and onSubmit problem in react js

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.

How do I add input validation and multiple error messages to sign up form?

I have one input validation implemented for the username, if the username already exists the error is put on the page. I would like to implement more input validations but I'm not sure how.
I want to validate that:
no fields can be left blank, and that
the password is not numbers (i.e. 1234 is not valid, the password has to be just alphabet characters like "password")
Here is my page:
import { Link, useHistory } from 'react-router-dom'
import { useState } from 'react'
const SignUp = ({ onSignup }) => {
let history = useHistory()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [first_name, setFirstName] = useState('')
const [last_name, setLastName] = useState('')
const [email, setEmail] = useState('')
const [admin, setAdmin] = useState(true)
const [error, setError] = useState(false)
const onSubmit = (e) => {
e.preventDefault()
// username already in use
if(!username) {
return
}
onSignup({ first_name, last_name, email, username, password, admin })
.then(() => {
history.push('/dashboard')
}).catch((err) => {
setError(true)
setUsername('')
setPassword('')
setFirstName('')
setLastName('')
setEmail('')
setAdmin(true)
})
}
return (
<div className='generalFormat'>
<div className='row justify-content-center'>
<div className='col-sm-10 col-md-6 col-lg-4'>
<div className='row'>
<h1>Sign Up</h1>
</div>
<div className='row'>
<form className='signupForm' onSubmit={onSubmit}>
{error && <p className='signupError'>This username is not available</p>}
<div>
<input
type='text'
placeholder='username'
className='form-control'
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div>
<input
type='text'
placeholder='password'
className='form-control'
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div>
<input
type='text'
placeholder='first name'
className='form-control'
value={first_name}
onChange={(e) => setFirstName(e.target.value)}
/>
</div>
<div>
<input
type='text'
placeholder='last name'
className='form-control'
value={last_name}
onChange={(e) => setLastName(e.target.value)}
/>
</div>
<div>
<input
type='text'
placeholder='email'
className='form-control'
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className='d-grid gap-2 mx-auto'>
<button className='btn btn-primary' type='submit'>Sign Up</button>
</div>
<Link to="/login">Already have an acount? Log In</Link>
</form>
</div>
</div>
</div>
</div>
)
}
export default SignUp
Here is a image of the error on the username

How to do routing by using Conditions in React

I am working on a React project, First I have to Signup then I stored Signup details in local storage so when I came to login screen after entering email and password and when I click submit button then it has to check the email and password from local storage. So if both are same then it should redirects to another page, I am trying to do this but it is showing some error so someone please help me to resolve this error
This is my code
This is Signup.js
import React, { useState, useRef } from 'react';
import './Signup.css';
const Signup = () => {
const [data, sendData] = useState({})
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
sendData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
localStorage.setItem('userInfo', JSON.stringify(data))
}
const myForm = useRef(null)
const resetForm = () => {
myForm.current.reset();
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='registerForm'>
<form onSubmit={handleSubmit} ref={myForm}>
<div className="form-group mb-2">
<label htmlFor="firstname">Firstname</label>
<input type="text" className="form-control" onChange={handleChange} name='firstname' id="firstname" placeholder="Enter firstname"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="lastname">Lastname</label>
<input type="text" className="form-control" onChange={handleChange} name='lastname' id="lastname" placeholder="Enter lastname"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" onChange={handleChange} name='email' id="email" placeholder="Enter email"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" onChange={handleChange} name='password' id="password" placeholder="Enter password"></input>
</div>
<button onClick={resetForm} type="submit" className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Signup
This is Login.js
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import './Login.css';
const Login = () => {
let history = useHistory();
if (login.email && login.password === signupCredentials.email && signupCredentials.password) {
var redirect = () => {
history.push('/dashboard')
}
}
const [login, setLogin] = useState({})
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, login, { [name]: value })
setLogin(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(login)
}
const signupCredentials = JSON.parse(localStorage.getItem('userInfo'))
console.log(signupCredentials.email && signupCredentials.password)
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group mb-2">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" onChange={handleChange} name='email' id="exampleInputEmail1" placeholder="Enter email"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="exampleInputPassword1">Password</label>
<input type="password" className="form-control" onChange={handleChange} name='password' id="exampleInputPassword1" placeholder="Password"></input>
</div>
<button type="submit" onClick={redirect} className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default Login
If you have any questions please let me know

Resources