xxxxxxxxxx
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) { this.setState({value: event.target.value}); }
handleSubmit(event) {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
xxxxxxxxxx
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;