Handling Complex Form

 Why Value is required?

It capture the value typed in the form and captures it for further use


Controlled Components vs Uncontrolled Components is very important - need to learn again


In its tutorial we have learnt how to reduce number of useState and use only one state.


This is somewhat tricky but regular practice will make it really easy.Thank you


import React, { useState } from 'react';

const App = () => {

const [fullName, setfullName] = useState({
fName: "",
lName: "",
});


const inputEvent = (event) => {
const Value= event.target.value;
const name = event.target.name;

setfullName((prevValue)=>{
if(name === 'fName')
{
return{
fName:Value,
lName:prevValue.lName,
}
}

else if (name ==='lName')
{ return{
fName:prevValue.fName,
lName:Value,
}

}
})


};




const onSubmit = (event) => {
event.preventDefault();

}



return (<>

<div>

<form onSubmit={onSubmit}>
<h1>Hello {fullName.fName} {fullName.lName}</h1>

<input type="text" placeholder="Enter your First Name" name="fName" value={fullName.fName}
onChange={inputEvent}
/><br />
<input type="text" placeholder="Enter your Last Name" name="lName" value={fullName.lName} onChange={inputEvent} /> <br />
<button type="submit">Click Me</button>



</form>

</div>

</>);
}

export default App;

Comments

Popular posts from this blog

Form Part 2

Event mini project by Thapa#33

De-mystifying 'this' keyword of Javascript