Languages
[Edit]
EN

React - how to use select

3 points
Created by:
Elias999
819

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 );

Alternative titles

  1. React - how to use combobox
  2. React - how to use dropdown
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

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.

❤️💻 🙂

Join