//The value coming from the input that triggered the event is getting updated in the state but not displaying in the browser, I don't really understand what's happening, I have been using the same method to update the state in my other project
import React, { useState } from "react";
const Register=()=>{
const [user,setUser]=useState({
name:"",
email:"",
password:"",
reenterPassword:""
});
let changeHandler=(e)=>{
const { name, value } = e.target
setUser({
...user,
[name]: value
})
}
return(
<div className="register">
<h1>Register</h1>
<input onChange={changeHandler} name="Username" placeholder="Please Enter Your Name" type="text" defaultValue="" value={user.name}/>
<input onChange={changeHandler} name="Email" placeholder="Enter your Email" type="email" value={user.email}/>
<input onChange={changeHandler} name="Password" placeholder="Create Your Password" type="password" value={user.password}/>
<input onChange={changeHandler} name="ReEnterPassword" placeholder="Re-Enter Your Password" type="password" value={user.reenterPassword}/>
<div className="button">Register</div>
<div>OR</div>
<div className="button">Login</div>
</div>
)
}
export default Register;
[1]: https://i.stack.imgur.com/G8beV.png
CodePudding user response:
there is good answer here about it: https://stackoverflow.com/a/58877875/2091359
you should not use useState like this, you can do useState for each input separately like this:
const [name, setName] = useState('')
const handleChangeName = (e) => {
setName(e.target.value);
}
return(
<div className="register">
<h1>Register</h1>
<input onChange={handleChangeName} name="Username" placeholder="Please Enter Your Name" type="text" value={name}/>
...
or use useReduce
CodePudding user response:
Try this code:
const Register=()=>{
const [user,setUser]=useState({
Username:"",
Email:"",
Password:"",
ReEnterPassword:""
});
let changeHandler=(e)=>{
const { name, value } = e.target
setUser({
...user,
[name]: value
})
}
return (
<div className="register">
<h1>Register</h1>
<input onChange={(e)=>changeHandler(e)} name="Username" placeholder="Please Enter Your Name" type="text" defaultValue="" value={user.name}/>
<input onChange={(e)=>changeHandler(e)} name="Email" placeholder="Enter your Email" type="email" value={user.email}/>
<input onChange={(e)=>changeHandler(e)} name="Password" placeholder="Create Your Password" type="password" value={user.password}/>
<input onChange={(e)=>changeHandler(e)} name="ReEnterPassword" placeholder="Re-Enter Your Password" type="password" value={user.reenterPassword}/>
<div className="button">Register</div>
<div>OR</div>
<div className="button">Login</div>
</div>
);
}
export default Register;
You need to use the same name for the html input attribute too, and try to use callback in the onChange event.