Let’s add a form in react. React uses forms to allow users to interact with the web page similar to HTML.
import React from 'react';
import ReactDOM from 'react-dom/client';
function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />); This form will submit and the page will refresh. But we want to prevent this default behavior and let React control the form.
In HTML, form’s data is handled by the DOM but in react the data is usually handled by components. When data is handled by the components, all the data is stored in the component state. We can control changes by adding event handlers in the onChange attribute.
We can use the useState Hook to keep track of each inputs value.
import { useState } from 'react';
import ReactDOM from 'react-dom/client';
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>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />); Multiple Input Fields
Create multiple Input Fields in react. You can control the values of more than on input field by adding a name attribute to each element.
To access the fields in the event handler use the event.target.name and event.target.value syntax.
import { useState } from "react";
import ReactDOM from "react-dom/client";
function MyForm() {
const [inputs, setInputs] = useState({});
const handleChange = (event) => {
const name = event.target.name;
const value = event.target.value;
setInputs(values => ({...values, [name]: value}))
}
const handleSubmit = (event) => {
event.preventDefault();
console.log(inputs);
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
name="username"
value={inputs.username || ""}
onChange={handleChange}
/>
</label>
<label>Enter your age:
<input
type="number"
name="age"
value={inputs.age || ""}
onChange={handleChange}
/>
</label>
<input type="submit" />
</form>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />); 