Created
April 3, 2020 14:20
-
-
Save binhtran04/c4ebd6608c770115306837b42730277e to your computer and use it in GitHub Desktop.
NewMovie 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
import React from 'react'; | |
import { useMoviesContext } from './MoviesContext'; | |
const getInitialMovieForm = () => { | |
return { | |
title: '', | |
year: '', | |
}; | |
}; | |
export const NewMovie = () => { | |
const [form, setForm] = React.useState(getInitialMovieForm); | |
const { addMovie } = useMoviesContext(); | |
const resetForm = () => { | |
setForm(getInitialMovieForm()); | |
}; | |
const handleSubmit = event => { | |
event.preventDefault(); | |
addMovie(form); | |
resetForm(); | |
}; | |
const handleChange = event => { | |
const { name, value } = event.target; | |
setForm(prev => ({ | |
...prev, | |
[name]: value, | |
})); | |
}; | |
return ( | |
<form className="NewMovie" onSubmit={handleSubmit}> | |
<input placeholder="Movie Title" name="title" value={form.title} onChange={handleChange} /> | |
<input placeholder="1995" type="number" name="year" value={form.year} onChange={handleChange} /> | |
<button type="submit">Add</button> | |
</form> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment