I want to use email value in resetPass function. How can I do that? - reactjs

I want to sent an email when reset password button is clicked. For that I have created a function named resetPass .I want to get email value in the function. How can I do that?
const Problem = () => {
const [
signInWithEmailAndPassword,
user,
loading,
error,
] = useSignInWithEmailAndPassword(auth, { sendEmailVerification: true });
//reset pass
const [sendPasswordResetEmail] = useSendPasswordResetEmail(
auth
);
//login button
//login button
const handleLogin = event => {
event.preventDefault();
const email = event?.target?.email?.value;
const password = event?.target?.password?.value;
signInWithEmailAndPassword(email, password)
}
//password reset
//password reset
const resetPass = () => {
//email: how to set email ???
sendPasswordResetEmail(auth, email)
.then(console.log('Email sent'))
}
return (
<div>
<Form onSubmit={handleLogin} className='w-50 mx-auto border p-5 m-5 bg-orange-200'>
<h2>Login</h2>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" name='email' placeholder="Enter email" required />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Password" name='password' required />
</Form.Group>
<h6>Forgot password? <button onClick={resetPass}>Reset Password</button></h6>
<Button variant="primary" type="submit">
Submit
</Button> <br />
<div>
<SocialLogin></SocialLogin>
</div>
</Form>
</div>
);
};
export default Problem;

Related

React app hanging when typing on input with onChange state

When I start typing anything in the input fields, the page hangs and nothing gets typed. It was working fine before, it just started happening suddenly. I don't know what went wrong.
I have tried adding onBlur and the problem persists. I tried adding value={registerEmail} in the input fields and the problem still remains as well.
Pleae check :(
import React, {useState} from 'react'
import {
createUserWithEmailAndPassword,
onAuthStateChanged,
signInWithEmailAndPassword,
signOut
} from 'firebase/auth'
import { Form, Button, Card, Container } from 'react-bootstrap'
import {auth} from '../../services/firebase-config'
export default function SignUp() {
const [registerEmail, setRegisterEmail] = useState("")
const [registerPassword, setRegisterPassword] = useState("")
const [registerConfirmedPassword, setRegisterConfirmedPassword] = useState("")
const [user, setUser] = useState({})
onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser)
})
const register = async (event) => {
event.preventDefault();
try {
const user = await createUserWithEmailAndPassword(auth, registerEmail, registerPassword)
console.log(user)
}
catch(error) {
//accounts that don't exist
console.log(error.message)
}
}
const login = async(event) => {
event.preventDefault();
try {
const user = await signInWithEmailAndPassword(auth, registerEmail, registerPassword)
console.log(user)
}
catch(error) {
//accounts that don't exist
console.log(error.message)
}
}
const logout = async(event) => {
try {
await signOut(auth)
}
catch(error) {
console.log(error.message)
}
}
return (
<Container className="d-flex align-items-center justify-content-center w-100">
<Card className='p-3' style={{maxWidth:"400px"}}>
<Card.Body>
<h2 className='text-center mb-4'>Sign Up</h2>
<Form>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" onChange={e => setRegisterEmail(e.target.value)} required />
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" onChange={e => setRegisterPassword(e.target.value)} required />
</Form.Group>
<Form.Group id="password-confirm">
<Form.Label>Password Confirmation</Form.Label>
<Form.Control type="password" onChange={e => setRegisterConfirmedPassword(e.target.value)} required />
</Form.Group>
{ <Button className='w-100' onClick={(e) => register(e)}>Sign Up</Button>}
</Form>
</Card.Body>
<div className='w-100 text-center mt-2'>
Already have an account? <Button className='w-100' onClick={(e) => login(e)}>Login</Button>
</div>
<Button onClick={(e) => logout(e)}>Logout</Button>
</Card>
</Container>
)
}
Value attr and Initial state was missing in the form.control
<Form>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control value={registerEmail} type="email" onChange={e => setRegisterEmail(e.target.value)} required />
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" value={registerPassword} onChange={e => setRegisterPassword(e.target.value)} required />
</Form.Group>
<Form.Group id="password-confirm">
<Form.Label>Password Confirmation</Form.Label>
<Form.Control type="password" onChange={e => setRegisterConfirmedPassword(e.target.value)} required />
</Form.Group>
{ <Button className='w-100' onClick={(e) => register(e)}>Sign Up</Button>}
</Form>
Example - codesandbox

How to reset form input filed after submit in react js

I want to clear input fields after clicking the submit button. I have used event.target.reset(); But it's not working. I have used React bootstrap form to get input values. Does any solution please? Check below my code.
const addItem = (event) => {
event.preventDefault();
const email = emailRef.current.value;
const name = nameRef.current.value;
const price = priceRef.current.value;
const data = {email, name, price, quantity, description, supplier_name, img }
const url = (`http://localhost:5000/myitems`);
axios.post(url, data)
.then(response =>{
const {data} = response;
if(data.insertedId){
toast('Your Item Added!');
event.target.reset();
}
})
}
return (
<div className='container mx-auto w-50'>
<h2 className='text-center my-3'>Add New Items</h2>
<div className=''>
<Form>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Control ref={emailRef} type="email" value={user?.email} placeholder="Enter email" disabled/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Control ref={nameRef} type="text" placeholder="Product Title" required/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Control ref={priceRef} type="number" placeholder="Price" required/>
</Form.Group>
<Button onClick={addItem} variant="primary" type="submit">
Add Item
</Button>
</Form>
</div>
</div>
);
};
export default AddItem;
Give the form an id. Then get the id of the form and run the reset() method.
document.getElementById("form-id").reset()
Also, you can give the form a ref. Then call the method current.reset()
const formRef = useRef(null);
<!-- your form -->
<form ref={formRef}>
...
</form>
Finally in your addItem() method, you can call the form ref to clear the form values.
formRef.current.reset()

Validation is not working for these and unable to write something in the forum

I am using this form from the react bootstrap. But when i am trying to validate it is not working. Can some one please help here and thanks in adavance.
but when i am trying to validate the username, email and phone, I am unable to do it also unable to write something in the forum, can some one please help me where i made exact error
import React, { useEffect, useState } from 'react'
import { Button, Col, Form, Row } from 'react-bootstrap';
const AddressValidation = () => {
const initialValues = { username: "", email: "", password: "" };
const [formValues, setFormValues] = useState(initialValues);
const [formErrors, setFormErrors] = useState({});
const [isSubmit, setIsSubmit] = useState(false);
const handleChange = (e) => {
const { name, value } = e.target;
setFormValues({ ...formValues, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
setFormErrors(validate(formValues));
setIsSubmit(true);
};
useEffect(() => {
console.log(formErrors);
if (Object.keys(formErrors).length === 0 && isSubmit) {
console.log(formValues);
}
}, [formErrors]);
const validate = (values) => {
const errors = {};
const regex = /^[^\s#]+#[^\s#]+\.[^\s#]{2,}$/i;
if (!values.username) {
errors.username = "Username is required!";
}
if (!values.email) {
errors.email = "Email is required!";
} else if (!regex.test(values.email)) {
errors.email = "This is not a valid email format!";
}
if (!values.username) {
errors.username= "usernameis required";
} else if (values.username.length < 4) {
errors.username= "username must be more than 4 characters and combination of 3 letters";
} else if (values.username.length > 10) {
errors.username= "username cannot exceed more than 10 characters";
}
return errors;
};
return (
<div className="container">
<pre>{JSON.stringify(formValues, undefined, 2)}</pre>
<Form onSubmit = { handleSubmit }>
<h1> Payment Validation Form</h1>
<Row className="mb-3">
<Form.Group as={Col} controlId="formGridUsername">
<Form.Label>User Name</Form.Label>
<Form.Control type="text" placeholder="Enter User Name" value={ formValues.username}
onChange = {handleChange}/>
</Form.Group>
<Form.Group as={Col} controlId="formGridEmail">
<Form.Label>Email</Form.Label>
<Form.Control type="email" placeholder="Enter email" value={ formValues.email}
onChange = {handleChange} />
</Form.Group>
<Form.Group as={Col} controlId="formGridPhone">
<Form.Label>phonenumber</Form.Label>
<Form.Control type="number" placeholder="Enter email" value={ formValues.phonenumber}
onChange = {handleChange} />
</Form.Group>
</Row>
<Form.Group className="mb-3" controlId="formGridAddress1">
<Form.Label>Address</Form.Label>
<Form.Control placeholder="1234 Main St" />
</Form.Group>
<Form.Group className="mb-3" controlId="formGridAddress2">
<Form.Label>Address 2</Form.Label>
<Form.Control placeholder="Apartment, studio, or floor" />
</Form.Group>
<Row className="mb-3">
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>City</Form.Label>
<Form.Control />
</Form.Group>
<Form.Group as={Col} controlId="formGridState">
<Form.Label>State</Form.Label>
<Form.Select defaultValue="Choose...">
<option>Choose...</option>
<option>Stockholm</option>
<option>Mälmo</option>
</Form.Select>
</Form.Group>
<Form.Group as={Col} controlId="formGridZip">
<Form.Label>Zip</Form.Label>
<Form.Control />
</Form.Group>
</Row>
<Form.Group className="mb-3" id="formGridCheckbox">
<Form.Check type="checkbox" label="Check me out" />
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
);
}
export default AddressValidation
You need to add the name property to your inputs. Otherweise you get an empty name property from event.target:
<Form.Control
name="username"
type="text"
placeholder="Enter User Name"
value={formValues.username}
onChange={handleChange}
/>
Your validation seems to work. When I try to submit, I can read the error messages in console:
{username: 'usernameis required', email: 'Email is required!'}

How to pass a data one Component to Another Components After Form Submit

In this code, I want to get my user email in Login Component after submitting the Registration Component.
Component: Registration
import React, { useState } from 'react';
import { Button, Container, Form,Row,Col } from 'react-bootstrap';
import { useNavigate,Navigate } from 'react-router-dom';
const Register = () => {
const [data,setData] = useState({
'first_name': 'dfdf',
'last_name': '',
'email': 'maruf#mail.com',
'password': '',
'password_confirm': ''
})
let navigate = useNavigate();
const handleInputChange = (e) => {
setData({
...data,
[e.target.name]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(data);
navigate('/login',{replace:true,state:{email:data.email}});
}
return <>
<Container fluid={'md'}>
<Row>
<Col xs={6}>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3" controlId="formBasicFirstName">
<Form.Label column >First Name</Form.Label>
<Form.Control name='first_name' value={data.first_name} onChange={handleInputChange} type="text" placeholder="First Name" />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicLastName">
<Form.Label>Last Name</Form.Label>
<Form.Control name='last_name' value={data.last_name} onChange={handleInputChange} type="text" placeholder="Last Name" />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control name='email' value={data.email} onChange={handleInputChange} type="email" placeholder="Enter email" />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control name='password' value={data.password} onChange={handleInputChange} type="password" placeholder="Password" />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword_Confirm">
<Form.Label>Password</Form.Label>
<Form.Control name='password_confirm' value={data.password_confirm} onChange={handleInputChange} type="password" placeholder="Confirm Password" />
</Form.Group>
<Button variant="primary" type='submit' onSubmit={handleSubmit} >Register</Button>
</Form>
</Col>
</Row>
</Container>
</>;
};
export default Register;
here I want to send the user email address after done the registration then send the data into the Login Components.
Component: Login
React, { useEffect, useState } from "react";
import { Button, Col, Container, Form, Row } from "react-bootstrap";
import { useLocation } from "react-router-dom";
import { Navigate, useNavigate } from "react-router-dom";
const Login = () => {
const [data,setData] = useState({
email: "",
password: "",
});
const uselocation = useLocation();
if (uselocation.state) {
if (uselocation.state.email) {
setData({
...data,
email: uselocation.state.email,
});
}
}
const handleSubmit = (e) => {
e.preventDefault();
console.log(data);
};
return (
<>
<Container fluid={'md'}>
<Row>
<Col xs={6}>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Password" />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Check me out" />
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</Col>
</Row>
</Container>
</>
);
};
export default Login;
after a navigate to login Component I got this error
Uncaught Error: Too many re-renders. React limits the number of
renders to prevent an infinite loop.
Wrap setData from Login component with useEffect and add location as a dependency.

How to add edit button and function in react.js

i want to share this question. So, i have a form which is designed by react-bootstrap. And also use React Hooks and React Function Component. I have a form which is add new form and delete form but i don't do edit form.
This is a return statement
return(
<Container>
<Row>
<Col>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control ref = {firstname} type="text" placeholder="Name.." />
</Form.Group>
<Form.Group>
<Form.Label>Surname</Form.Label>
<Form.Control ref = {secondname} type="text" placeholder="Surname.." />
</Form.Group>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control ref = {email} type="email" placeholder="E-Mail" />
<Form.Text> Please, Enter like "asd#asd.com"</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Comment</Form.Label>
<Form.Control ref = {comment} as="textarea" rows={3} placeholder = "Notes :)"/>
</Form.Group>
<Button className = "btn-lg" onClick={handleSubmit} variant="success" type="submit">Submit</Button>
</Form>
</Col>
</Row>
{Formss}
</Container>
)
And then, These are the function of this return
const Formss = input.map((item , index) =>
{
return(
<Lists key = {index} item = {item} index = {index} deleteFunc={handleDelete}/>
)
}
)
const handleSubmit = (event) => {
event.preventDefault();
const name = firstname.current.value
const surname = secondname.current.value
const mail = email.current.value
const mycomment = comment.current.value
const data = {id:id(),
name : name,
surname : surname,
mail : mail,
mycomment : mycomment}
if(data.name && data.surname && data.mail && data.mycomment){
setInput([...input, data])
firstname.current.value = ""
secondname.current.value = ""
email.current.value = ""
comment.current.value =""
}else{
console.log("oopss")
}
}
I use ref hook for handleSubmit. So, How to add edit button and edit function?
To be able to edit data, and to save it in state you can do it as in provided example. Then in handleSubmit function you can process your data further:
import React from "react";
import { Container, Row, Col, Form, Button } from "react-bootstrap";
const App = () => {
const handleSubmit = (e) => {
e.preventDefault();
console.log(state);
};
const initialState = {
firstname: "",
secondname: "",
email: "",
comment: "",
};
const [state, setState] = React.useState(initialState);
const handleChange = ({ target: { value, name } }) => {
setState({ ...state, [name]: value });
};
return (
<Container>
<Row>
<Col>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control
name="firstname"
value={state.firstname}
type="text"
placeholder="Name.."
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Surname</Form.Label>
<Form.Control
name="secondname"
value={state.secondname}
type="text"
placeholder="Surname.."
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control
value={state.email}
name="email"
type="email"
placeholder="E-Mail"
onChange={handleChange}
/>
<Form.Text> Please, Enter like "asd#asd.com"</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Comment</Form.Label>
<Form.Control
name="comment"
value={state.comment}
as="textarea"
rows={3}
placeholder="Notes :)"
onChange={handleChange}
/>
</Form.Group>
<Button className="btn-lg" variant="success" type="submit">
Submit
</Button>
</Form>
</Col>
</Row>
</Container>
);
};
export default App;

Resources