I making a select option using react-select following this Installation and usage example code.
There was an object of array to store the option like this:
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
Now, I want to make it dynamically to store the value from other data and make it iterate on the object.
like this:
const options = [
{ value: flavor, label: flavor },
];
The flavor on the value and the label are an array. Let's say the array was store the data like this:
flavor = ['chocolate', 'strawberry', 'vanilla']
So, whenever the array added new value, the object of array above also add the value on the iterate.
So, how to making iterate in that..?
or should I thinking to figure out in the component..?
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
EDIT: the result what I want are the object inside the array is added according to the array values, let's say if we have one data inside array, then the const options
store data like this:
const options = [
{ value: flavor, label: flavor },
];
then if the array store 2 data, then the const options
be like this:
const options = [
{ value: flavor, label: flavor },
{ value: flavor, label: flavor },
];
The purpose of this are for make dropdown options on the select have dynamically values.
You can use an .map
function to dynamically created your options :)
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
const options = [
{ value: 'flavor', label: 'flavor' },
{ value: 'yummy', label: 'yummy' },
{ value: 'red', label: 'red' },
{ value: 'green', label: 'green' },
{ value: 'yellow', label: 'yellow' },
];
class App extends Component {
state = {
selectedOption: 'None',
}
handleChange = ({ target }) => {
this.setState({
selectedOption: target.value,
});
}
render = () => (
<div>
<span>{this.state.selectedOption}</span>
<select
value={this.state.selectedOption}
onChange={this.handleChange}
>
{options.map(({ value, label }, index) => <option value={value} >{label}</option>)}
</select>
</div>
);
}
render(<App />, document.getElementById('root'));
Working example here https://stackblitz.com/edit/react-select-example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With