React - how to use select

3 points
Created by:
Dirask Community

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 => {
    const data = {
      color: colorRef.current.value
    const json = JSON.stringify(data);
  return (
    <form onSubmit={handleSubmit}>
          Choose your favorite color:
          <select ref={colorRef}>
            <option value='red'>Red</option>
            <option value='yellow'>Yellow</option>
            <option value='blue'>Blue</option>
      <button type='submit'>Submit</button>

const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );


React - how to use select
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé