JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Handling onChange events on Select elements in React

Author:JIYIK Last Updated:2025/03/17 Views:

onChangeTo handle events on the select element in React :

  1. Set the attribute on the select element onChange.
  2. Save the value of the selected option in a state variable.
  3. Each time the user changes the selected option, update the state variable.
import {useState} from 'react';

const App = () => {
  const options = [
    {value: '', text: '--Choose an option--'},
    {value: 'apple', text: 'Apple 🍏'},
    {value: 'banana', text: 'Banana 🍌'},
    {value: 'kiwi', text: 'Kiwi 🥝'},
  ];

  const [selected, setSelected] = useState(options[0].value);

  const handleChange = event => {
    console.log(event.target.value);
    setSelected(event.target.value);
  };

  return (
    <div>
      <select value={selected} onChange={handleChange}>
        {options.map(option => (
          <option key={option.value} value={option.value}>
            {option.text}
          </option>
        ))}
      </select>
    </div>
  );
};

export default App;

Handling onChange events on Select elements in React

This example defines all options in an array to make our JSX code more concise, but we could write each option element manually.

If we prefer to enter the options manually, check out the last code snippet in the article.

We use useStatethe hook to store the value of the selected option.

The argument we pass to the hook is the initial state. In the example, we set the value of the initial selection to an empty string, which is the value of the first option element.

If we want a different option to be initially selected, pass its value to useStatethe hook.

We set the attribute on the selectonChange element , so every time its value changes, handleChangethe function will be called.

const handleChange = event => {
  console.log(event.target.value);
  setSelected(event.target.value);
};

The target property of the event object refers to the select element, so we can access the selected value as event.target.value.

In our handleChangefunction, we simply update the state with the value of the selected option.

If we need to get the text associated with the selected option element, access the label attribute of the selected option.

const handleChange = event => {
  console.log('Label 👉️', event.target.selectedOptions[0].label);

  console.log(event.target.value);
  setSelected(event.target.value);
};

Here is an example of how to map()manually enter the options for a select element without using .

import {useState} from 'react';

const App = () => {
  // 👇️ initial value of empty string (first option)
  const [selected, setSelected] = useState('');

  const handleChange = event => {
    console.log('Label 👉️', event.target.selectedOptions[0].label);
    console.log(event.target.value);
    setSelected(event.target.value);
  };

  return (
    <div>
      <select value={selected} onChange={handleChange}>
        <option value="">--Choose and option--</option>
        <option value="apple">Apple 🍏</option>
        <option value="banana">Banana 🍌</option>
        <option value="kiwi">Kiwi 🥝</option>
      </select>
    </div>
  );
};

export default App;

We set an initial value of an empty string for selectthe element, which will render the first option.

We can change the default selected option by providing a different initial value, such as apple .

Make sure the initial value is one of the possible values ​​for the attribute optionon the element value.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:166 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial