React, like HTML, uses forms to allow users to interact with online pages.
You may add a form to React like any other element:
Add a form where people can enter their names:
function MyForm() {
return (
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
This will proceed normally, with the form being submitted and the website refreshing.
However, this is not the desired outcome in React.
We want to disable the default behavior and let React control the form.
Handling forms refers to how you handle data as it changes value or is submitted.
In HTML, form data is typically handled by the DOM.
In React, form data is typically handled by components.
When data is handled by components, it is all saved in the component’s state.
You can control changes by specifying event handlers in the onChange attribute.
The useState Hook allows us to keep track of each input value and create a “single source of truth” for the entire program.
Hooks are discussed in further detail in the React Hooks section.
Use the useState Hook to manage the input.
To control the submit action, add an event handler to the onSubmit attribute of the <form>.
Add a submit button and an event handler to the onSubmit attribute.
You can control the values of multiple input fields by assigning a name attribute to each element.
We’ll start our state with an empty object.
To access the event handler’s fields, use the event.target.name and event.target.value syntax.
To change the status, place square brackets [bracket notation] around the property name.
Create a form containing two input fields:
Note: We use the same event handler function for both input fields; we could create one for each, but this results in much cleaner code and is the preferred method in React.
The textarea element in React differs slightly from standard HTML.
In HTML, a textarea’s value was the text between the start tag <textarea> and end tag </textarea>.
In React, the value of a textarea is stored in the value attribute. To manage the textarea’s value, we’ll utilize the useState Hook.
A simple textarea with some content:
A drop down list, also known as a pick box in React, differs from HTML.
In HTML, the selected value in the drop down list was defined with the choose attribute:
In React, the selected value is defined by the value attribute on the choose tag:
A simple select box, with the selected value “Volvo” initialized in the constructor:
Making little tweaks to <textarea> and <select> allows React to handle all input components uniformly.
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.