EN
React - how to pass array of options to select
3
points
In this article, we would like to answer for the question: How to set options
array in <select>
element in React.
The answer is: by default <select>
element doesn't provide options
property, so we should put <options>
elements inside <select>
element or create simple <Select>
component, what was shown in the article.
Quick solution:
const options = [
{value: 'value-1', text: 'text-1'},
{value: 'value-2', text: 'text-2'},
{value: 'value-3', text: 'text-3'}
];
<select value="value-2" onChange={handleChange}>
{options.map(item => {
return (<option key={item.value} value={item.value}>{item.text}</option>);
})}
</select>
Practical examples
Simple select usage example
This section contains <select>
with nested <option>
elements inside like in classic HTML.
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const colors = [
{value: 'red', text: 'Red' },
{value: 'yellow', text: 'Yellow'},
{value: 'blue', text: 'Blue' }
];
const App = () => {
const [color, setColor] = React.useState('red');
const handleChange = e => setColor(e.target.value);
const handleSubmit = e => {
e.preventDefault();
const data = {
color: color
};
const json = JSON.stringify(data);
console.clear();
console.log(json);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>
Choose your favorite color:
<select value={color} onChange={handleChange}>
{colors.map(item => {
return (<option key={item.value} value={item.value}>{item.text}</option>);
})}
</select>
</label>
</div>
<button type='submit'>Submit</button>
</form>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Custom select component example
This section we use custom <Select>
component that lets us to pass options
as array in property.
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const Select = ({value, options, onChange}) => {
return (
<select value={value} onChange={onChange}>
{options.map(option => {
return (<option key={option.value} value={option.value}>{option.text}</option>);
})}
</select>
);
};
const colors = [
{value: 'red', text: 'Red' },
{value: 'yellow', text: 'Yellow'},
{value: 'blue', text: 'Blue' }
];
const App = () => {
const [color, setColor] = React.useState('red');
const handleChange = e => setColor(e.target.value);
const handleSubmit = e => {
e.preventDefault();
const data = {
color: color
};
const json = JSON.stringify(data);
console.clear();
console.log(json);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>
<span>Choose your favorite color:</span>
<Select value={color} options={colors} onChange={handleChange} />
</label>
</div>
<button type='submit'>Submit</button>
</form>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);