How to create a Select element in React?

About

This page is about the creation of a HTML select element in React 1) and how to handle it in a form

Type

Non-Controlled Component

In a non-controlled fashion, you need to read the value from the HTML select DOM element.

form implementing a non-controlled component written as a function component

Example:

  • The uncontrolled component
const SelectForm = () => {

  const handleChange = (event) => {
    console.log('Your favorite color was changed to: ' + event.target.value);
  }

  function handleSubmit(e) {

    // Prevent the browser from reloading the page
    e.preventDefault();
    
    // Read the form data
    const form = e.target;
    const formData = new FormData(form);
    const formJson = Object.fromEntries(formData.entries());
    console.log('Your favorite color was submitted to: ' + formJson.color);

    // Note you can pass formData as a fetch body directly:
    // fetch('/some-api', { method: form.method, body: formData });
    // You can generate a URL out of it, as the browser does by default:
    // console.log(new URLSearchParams(formData).toString());
    // Or you can get an array of name-value pairs.
    // console.log([...formData.entries()]);
    
  }


    return (
      <form onSubmit={handleSubmit}>
        <label>
          Pick your favorite color:
          <select name="color" defaultValue="green" onChange={handleChange}>
            <option value="green">Green</option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="yellow">Yellow</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
}
ReactDOM.render(
  <SelectForm />,
  document.getElementById('root')
);
<div id="root"></div>
  • Result:

Controlled Component

This page shows you to do it as a controlled component. It means that the value attribute of the HTML select element is controlled by React.

form implementing a controlled component written as a function component

Example:

  • The controlled component
const SelectForm = () => {

  const [color, setColor] = React.useState('blue');

  const handleChange = (event) => {
    setColor(event.target.value);
    console.log('Your favorite color was changed to: ' + event.target.value);
  }

  const handleSubmit = (event) => {
    console.log('Your favorite color was submitted to : ' + color);
    event.preventDefault();
  }

    return (
      <form onSubmit={handleSubmit}>
        <label>
          Pick your favorite color:
          <select 
            value={color} // the actual value
            defaultValue={color} // the default value if select value is undefined
            onChange={handleChange}>
            <option value="green">Green</option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="yellow">Yellow</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
}
ReactDOM.render(
  <SelectForm />,
  document.getElementById('root')
);
<div id="root"></div>
  • Result:

Library

There are libraries that wrap up the HTML select element to add features. A select is just a dropdown after all.

Example:

Archive

Controlled Component Example with a Class Component

form implementing a controlled component written as a class component

class SelectForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'green'};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    console.log('Your favorite color is: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite color:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="green">Green</option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="yellow">Yellow</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(
  <SelectForm />,
  document.getElementById('root')
);
<div id="root"></div>





Discover More
How to create a React Select Component with Typescript and a collection of objects?

This page shows you a minimal example of the React Select library (a React select element) with Typescript. React select can handle any list of objects. The essential...
How to use the Select HTML Element?

select is an HTML control form element used for selecting one or more value amongst a set of options. It creates a drop-down list used in a form that will set a scalar value from a list of options. ...
React - Controlled Component

A controlled component is a component such as a form element where its state is controlled by React. uncontrolled component In a controlled component, state is handled by the React component The nature...
What are React Forms?

A React form is the implementation of HTML form elements with HTML React elements It works a little bit differently from other DOM elements in React, because form elements naturally keep some internal...



Share this page:
Follow us:
Task Runner