Languages
[Edit]
EN

React - how to use select

3 points
Created by:
Dirask Community
6930

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

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