Created
May 8, 2024 06:47
-
-
Save mishaj-7/920d622595adb59c90386428f2a555b8 to your computer and use it in GitHub Desktop.
controlled component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const BookForm = () => { | |
const { addBook } = useContext(BookContext); | |
const [data, setData] = useState({ | |
title: "", | |
author:"", | |
}) | |
const handleChange = (e) => { | |
const { value, name } = e.target | |
setData((prev) => { | |
return { | |
...prev, | |
[name]: value, | |
}; | |
}); | |
}; | |
const handleSubmit = (e) => { | |
const { title, author } = data; | |
e.preventDefault(); | |
addBook(title, author); | |
setData({title:'',author:''}) | |
} | |
return ( | |
<form onSubmit={handleSubmit}> | |
<input | |
type="text" | |
placeholder="book title" | |
value={data.title} | |
onChange={handleChange} | |
name="title" | |
required | |
/> | |
<input | |
type="text" | |
placeholder="author" | |
value={data.author} | |
onChange={handleChange} | |
name="author" | |
required | |
/> | |
<input type="submit" value='Add' /> | |
</form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment