Select - Reactjs Component

Author - Select - ReactJS Component
Cristian
September 3rd, 2020
Select - ReactJS Component

Select - ReactJS Component

It renders an <select> element that uses a callback function to pass its value to the parent component.

We use object destructuring to set defaults for certain attributes of the <select> component. 

const Select = ({ 
  options, 
  callback, 
  disabled = false, 
  readonly = false, 
  selected, 
}) => {
  return (
    <select
      disabled={disabled}
      readOnly={readonly}
      onChange={({ target : { value } }) => callback(value)}
    >
      {options.map(([value, text]) => <option selected={selected === value}value={value}>{text}</option>)}
    </select>
  );
}
let options = [
  ['1', 'First'],
  ['2', 'Second'],
  ['3', 'Third'],
];
ReactDOM.render(
  <Select 
    options={options} 
    selected='3' 
    callback={(val) => console.log(val)
  }/>,
  document.getElementById('root')
);