Changing complex state in React (react forms)
import React, { useState } from "react";
function Ap(){
const [Fname,Setname] = useState("");
const [Lname,Stname] = useState("");
function update(event){
Setname(event.target.value);
}
function updateLname(event){
Stname(event.target.value);
}
return(
<>
<h1>Hello {Fname} {Lname}</h1>
<input type="text" name = "Fname" onChange={update}
placeholder="First Name" value = {Fname}/>
<input type="text" name = "Lname" onChange={updateLname}
placeholder="Last Name" value = {Lname} />
<button>Submit</button>
</>
)
}
export default Ap;
///////////////////////////////////////////////////////////////////////
Right way or after destructing
import React, { useState } from "react";
function Ap(){
const [Fullname,Setname] = useState({
Fname:"",
Lname:""
});
function update(event){
const {value,name} = event.target;
Setname(prevValue =>{
if(name === "Fname"){
return{
Fname:value,
Lname:prevValue.Lname
};
}else if(name === "Lname"){
return{
Fname:prevValue.Fname,
Lname:value
};
}
})
}
return(
<>
<h1>Hello {Fullname.Fname} {Fullname.Lname}</h1>
<input type="text" name = "Fname" onChange={update} placeholder="First Name" value = {Fullname. Fname}/>
<input type="text" name = "Lname" onChange={update} placeholder="Last Name" value = {Fullname.Lname}/>
<button>Submit</button>
</>
)
}
export default Ap;
Comments
Post a Comment