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. In React, often, 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 component is called a controlled component because form data is handled by React. In an uncontrolled component, the form data is handled only by the DOM.
The setText(event.target.value)
statement gets the value from the input
field and saves it to the state. Finally, we will show the...