-- Main.shssdhakchina - 02 Feb 2022
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:
Example:
Add a form that allows users to enter their name:
function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
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.
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.
We can use the useState Hook to keep track of each inputs value and provide a "single source of truth" for the entire application.
Example:
Use the onChange Hook to manage the input:
import { useState } from "react";
import ReactDOM from 'react-dom';
function MyForm() {
const [name, setName] = useState("");
return (
<form>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
You can control the submit action by adding an event handler in the onSubmit attribute for the