Loading lesson path
Just like in HTML, React uses forms to allow users to interact with the web page.
You add a form with React like any other element:
Add a form that allows users to enter their name:
function MyForm() {
return (<form>
Formula
< label > Enter your name:<input type="text" /> </label> </form> )
}createRoot(document.getElementById('root')).render( <MyForm />
);This will work as normal, the form will submit and the page will refresh. But this is generally not what we want to happen in React.
We want to prevent this default behavior and let React control the form.HTML Forms vs. React Forms In React, form elements like <input>, <textarea>, and <select> work a bit differently from traditional HTML. In standard HTML, form elements maintain their own value based on user input. For example, an <input type="text"> field keeps track of its own value in the HTML DOM. In React, the value of the form element is kept in the component's state property and updated only with the setState () function.
In other words; React provides a way to manage form data through component state, leading to what are known as "controlled components."In a controlled component, form data is handled by the React component. The value of the input element is driven by the React state, and any changes to that value are managed through event handlers that update the state. When the data is handled by the components, all the data is stored in the component state.
Hook to keep track of each input value and provide a "single source of truth" for the entire application.
React Hooks section for more information on Hooks.
import { useState } from 'react';
import { createRoot } from 'react-dom/client';function MyForm() {
const [name, setName] = useState("");function handleChange(e) {
setName(e.target.value);
}return (<form>
Formula
< label > Enter your name:<input type="text"
value={name}
onChange={handleChange}/> </label>
<p>Current value: {name}</p></form> )
}createRoot(document.getElementById('root')).render( <MyForm />
);Example »
import { useState } from 'react';const [name, setName] = useState("");function handleChange(e) {
setName(e.target.value);
}value={name}
onChange={handleChange}/>
<p>Current value: {name}</p>To add an initial value to the input field in the example above, add a value to the useState object:
function MyForm() {
const [name, setName] = useState("John");...
Example »