1.4 KiB
1.4 KiB
title, tags, expertise, cover, firstSeen, lastUpdated
| title | tags | expertise | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Uncontrolled select element | components,input | beginner | blog_images/down-the-stream.jpg | 2018-12-10T10:48:03+02:00 | 2020-11-25T20:46:35+02:00 |
Renders an uncontrolled <select> element that uses a callback function to pass its value to the parent component.
- Use the the
selectedValueprop as thedefaultValueof the<select>element to set its initial value.. - Use the
onChangeevent to fire theonValueChangecallback and send the new value to the parent. - Use
Array.prototype.map()on thevaluesarray to create an<option>element for each passed value. - Each item in
valuesmust be a 2-element array, where the first element is thevalueof the item and the second one is the displayed text for it.
const Select = ({ values, onValueChange, selectedValue, ...rest }) => {
return (
<select
defaultValue={selectedValue}
onChange={({ target: { value } }) => onValueChange(value)}
{...rest}
>
{values.map(([value, text]) => (
<option key={value} value={value}>
{text}
</option>
))}
</select>
);
};
const choices = [
['grapefruit', 'Grapefruit'],
['lime', 'Lime'],
['coconut', 'Coconut'],
['mango', 'Mango'],
];
ReactDOM.render(
<Select
values={choices}
selectedValue="lime"
onValueChange={val => console.log(val)}
/>,
document.getElementById('root')
);