In React, the textarea element differs slightly from ordinary HTML. In HTML, the value of a textarea is the text between the <textarea> start tag and the </textarea> end tag.
<textarea> Content of the textarea. </textarea>
|
In React, the value of a textarea
is set using the value
attribute. We’ll use the useState
Hook to manage this value.
Example:
A basic textarea with initial content.
import { useState } from 'react';
import ReactDOM from 'react-dom/client';
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>
) }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<MyForm />);
|
Select
In React, a drop-down list or select box differs slightly from HTML. In HTML, the selected value in a drop-down list is specified using the selected attribute.
HTML:
<select>
<option value="Ford">Ford </option>
<option value="Volvo" selected>Volvo </option>
<option value="Fiat">Fiat </option>
</select>
|
In React, the selected value is specified using the value attribute on the select tag.
Example:
A basic select box, with the selected value “Volvo” initialized in the constructor.
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>
) }
|
By making these minor adjustments to <textarea> and <select>, React can handle all input elements uniformly.