I have some data and form inputs, I need to prefill the existing data in the fields and when click on edit I like to edit the data and submit it to the state on button click
const data = {
name: "nazar",
email: "[email protected]",
phone: 123456789
};
const [ editData, setEditData ] = useState()
function handleEdit(){
}
function handleSubmit(){
}
<form onChange={handleEdit}>
<input type="text" name='name'/><button>Edit</button><br/>
<input type="text" name='email'/><button>Edit</button><br/>
<input type="text" name='phone'/><button>Edit</button><br/>
<button type='submit' onSubmit={handleSubmit}>Submit</button>
</form>
CodePudding user response:
// declare your data as initial state
const [data, setData] = React.useState({
name: 'nazar',
email: '[email protected]',
phone: 123456789,
});
// handle on change according to input name and setState
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault()
// take data to submit
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={data.name} // inject state correspond to input and so on
onChange={handleChange}
/>
<button>Edit</button>
<br />
<input
type="text"
name="email"
value={data.email}
onChange={handleChange}
/>
<button>Edit</button>
<br />
<input
type="text"
name="phone"
value={data.phone}
onChange={handleChange}
/>
<button>Edit</button>
<br />
<button type="submit">
Submit
</button>
</form>
</div>
);