EN
React - how to use select
3
points
In this article we would like to show you how to use select
element in React.
In below example we use React.useRef
hook to create colorRef
reference to the select
element in which we choose our favorite color from red
, yellow
or blue
option
.
Inside handleSubmit
function data
object is created using DOM reference to the select
element with colorRef.current.value
property.
Finally handleSubmit
function displays in the console our data
object converted to JSON.
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
//import React from 'react';
const Form = () => {
const colorRef = React.useRef();
const handleSubmit = e => {
e.preventDefault();
const data = {
color: colorRef.current.value
};
const json = JSON.stringify(data);
console.clear();
console.log(json);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>
Choose your favorite color:
<select ref={colorRef}>
<option value='red'>Red</option>
<option value='yellow'>Yellow</option>
<option value='blue'>Blue</option>
</select>
</label>
</div>
<button type='submit'>Submit</button>
</form>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );