Forms
Just like in HTML , React uses forms to allow users to interact with the web page.
Adding Forms in React
You add a form with React like any other element :
Example :
Add a form that allows users to enter their name :
Handling Forms
Handling forms is about how you handle the data when it changes value or gets submitted.
In HTML, form data is usually handled by the DOM.
In React, form data is usually handled by the components.
When the data is handled by the components, all the data is stored in the component state.
You can control changes by adding event handlers in the onChange attribute :
Example :
Note : You must initialize the state in the constructor method before you can use it.
Note : You get access to the field value by using the event.target.value syntax.
Conditional Rendering
If you do not want to display the h1 element until the user has done any input, you can add an if statement.
Look at the example below and note the following :
- We create an empty variable, in this example, we call it header .
- We add an if statement to insert content to the header variable if the user has done any input.
- We insert the header variable in the output, using curly brackets.
Submitting Forms
You can control the submit action by adding an event handler in the onSubmit attribute:
Note that we use event.preventDefault() to prevent the form from actually being submitted.
Multiple Input Fields
You can control the values of more than one input field by adding a name attribute to each element.
When you initialize the state in the constructor, use the field names.
To access the fields in the event handler use the event.target.name and event.target.value syntax.
To update the state in the this.setState method, use square brackets [bracket notation] around the property name.
Textarea
The text area element in React is slightly different from ordinary HTML.
In HTML the value of a text area was the text between the start tag <textarea> and the end tag </textarea> , in React the value of a text area is placed in a value attribute :
Select
A drop-down list, or a select box, in React is also a bit different from HTML.
In React, the selected value is defined with a value attribute on the select tag :