Handling forms with React
Form handling is a little bit different with React. An HTML form
will navigate to the next page when it is submitted. Oftentimes, we want to invoke a JavaScript function that has access to form data after submission and avoid navigating to the next page. We already covered how to avoid submission in the previous section using preventDefault()
.
Let's first create a minimalistic form with one input field and a Submit button. In order to get the value of the input field, we use the onChange
event handler. We use the useState
hook to create a state variable called text
. When the value of the input field is changed, the new value will be saved to the state. This is also called a controlled component because form data is handled by React.
The setText(event.target.value)
statement gets the value from the input
field and saves it to the state. Finally, we will show the typed value when a user presses the Submit button. Here is the source code for our first...