Handling onChange events on Select elements in React
onChange
To handle events on the select element in React :
-
Set the attribute on the select element
onChange
. - Save the value of the selected option in a state variable.
- 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;
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 useState
the 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
useState
the hook.
We set the attribute on the selectonChange
element , so every time its value changes, handleChange
the 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 handleChange
function, 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 select
the 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 option
on 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.
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.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
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.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu