Table of Contents

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>