Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Select - setState of prop

I am trying to set the state of my brandSelect prop in ReactJS using React Select however I am confused to how this can be done?

Here is my current code:

class VehicleSelect extends React.Component {

  constructor(props) {
    super(props);

    this.state = { brandSelect: ""};

  }
  render() {
    var options = [
    { value: 'Volkswagen', label: 'Volkswagen' },
    { value: 'Seat', label: 'Seat' }
    ];


    return (
      <Select
          name="form-field-name"
          value={this.state.brandSelect}
          options={options}
          placeholder="Select a brand"
          searchable={false}
          onChange={}
      />
    )
  }
};

When the option is selected I want the state to be set as the option chosen.

Does anybody know how this is done with React Select as the documentation doesn't really cover this? So far I have tried making a function with a set state attached to the onChange prop however this didn't work.

like image 747
Nick Maddren Avatar asked Mar 18 '26 16:03

Nick Maddren


1 Answers

In react 16.8+ the implementation should look like this using React hooks:

Hooks are a new addition in React 16.8

function VehicleSelect() {

  const options = [
    { value: 'volkswagen', label: 'Volkswagen' },
    { value: 'seat', label: 'Seat' }
  ];

  const [selectedOption, setSelectedOption] = useState({ value: 'volkswagen', label: 'Volkswagen' });

  const [handleChange] = useState(() => {
    return () => {
      setSelectedOption(selectedOption);
    };
  });

  return (
    <div className="App">
      <Select
        name="form-field-name"
        placeholder="Select a brand"
        searchable={false}
        value={selectedOption}
        onChange={handleChange}
        options={options}
      />
    </div>
  );
}
like image 60
ROOT Avatar answered Mar 21 '26 06:03

ROOT