How to create a form in ReactJS
React uses forms to allow users to interact with the web page, just like in HTML.
Code Sample:
function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
The example above will work as normal, the form will submit, and the page will refresh. But it's not how we want it in React. So, we want to prevent this default behavior and let React control the form.
Now you will be thinking how handling a form in React will look like. Handling forms is about how you handle the data when it changes value or gets submitted. Normally In HTML, form data is usually handled by the DOM. But In React, form data is typically handled by the components. That is, when the data is handled by the components, all the data is stored in the component state. Changes can be controlled 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.
Here is a minimal code sample:
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'));
Now you might be thinking that how can you handle the submitting part of the form.
You can get this done by adding an event handler in the onSubmit
attribute for the <form>
Here is a minimal code sample:
import { useState } from "react";
import ReactDOM from 'react-dom';
function MyForm() {
const [name, setName] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
alert(`The name you entered was: ${name}`)
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Now let's discuss how you can create multiple input fields in a form.
This can be done by controlling the values of more than one input field by adding a name
attribute to each element.
Now to access the fields in the event handler use the event.target.name
and event.target.value
syntax. And to also update the state, use square brackets [bracket notation] around the property name.
Code Sample:
import { useState } from "react";
import ReactDOM from "react-dom";
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();
alert(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>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Note: We use the same event handler function for both input fields, we could write one event handler for each, but this gives us much cleaner code and is the preferred way in React.
Some may ask within themselves that how can we get <textarea>
done in React. Here I'm going to explain in a very simple way. The textarea element in React is slightly different from ordinary HTML.
We all know that In HTML the value of a textarea was the text between the start tag
<textarea> and the end tag </textarea>
.
<textarea>
Content of the textarea.
</textarea>
But In React the value of a textarea is placed in a value attribute.
We'll use the useState
Hook to manage the value of the textarea.
Code Sample:
import { useState } from "react";
import ReactDOM from "react-dom";
function MyForm() {
const [textarea, setTextarea] = useState(
"The content of a textarea goes in the value attribute"
);
const handleChange = (event) => {
setTextarea(event.target.value)
}
return (
<form>
<textarea value={textarea} onChange={handleChange} />
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Lastly, let's discuss on how we can create a select box, dropdown list in React.
A dropdown list, or a select box, in React is also a bit different from HTML. In HTML, the selected value in the dropdown list was defined with the selected attribute.
<select>
<option value="Ford">Ford</option>
<option value="Volvo" selected>Volvo</option>
<option value="Fiat">Fiat</option>
</select>
But in React the selected value is defined with a value attribute on the select tag.
Here is a Code Sample:
import { useState } from "react";
import ReactDOM from "react-dom";
function MyForm() {
const [myCar, setMyCar] = useState("Volvo");
const handleChange = (event) => {
setMyCar(event.target.value)
}
return (
<form>
<select value={myCar} onChange={handleChange}>
<option value="Ford">Ford</option>
<option value="Volvo">Volvo</option>
<option value="Fiat">Fiat</option>
</select>
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Note: By making these slight changes to <textarea>
and <select>
, React is able to handle all input elements in the same way.
Thanks for reading to the end. I believe you gain some knowledge from the article.