Home > Enterprise >  Programmatically select an option with react-select
Programmatically select an option with react-select

Time:09-01

I have a basic understanding of React. I'm using react-select and I want to programmatically select an option. For example, with the code below, how to select option B on clicking the button?

This page mentions a setValue function, but I don't understand how to use it. I don't know what is a "ref" in React and how to use it, and I found similar questions on SO with answers assuming this knowledge.

import { useState } from "react";
import Select from "react-select";

const options = [
  { value: "A", label: "A" },
  { value: "B", label: "B" }
];

export default function App() {
  const [selectedOption, setSelectedOption] = useState("A");

  const handleChange = (value) => {
    setSelectedOption(value);    
  };

  return (
    <div className="App">
      <Select
        value={selectedOption}
        onChange={handleChange}
        options={options}
      />
      <button onClick={() => ????????}>Select B</button>
    </div>
  );
}

CodePudding user response:

You can use the following code.

import { useState } from "react";
import Select from "react-select";

const options = [
  { value: "A", label: "A" },
  { value: "B", label: "B" }
];

export default function App() {
  const [selectedOption, setSelectedOption] = useState(options[0]);

  const handleChange = (value) => {
    setSelectedOption(value);    
  };

  return (
    <div className="App">
      <Select
        value={selectedOption}
        onChange={handleChange}
        options={options}
      />
      <button onClick={() => setSelectedOption(options[1])}>Select B</button>
    </div>
  );
}

React-Select is different with Select from Material UI. React-Select receives the object of options and set, display the value according to the object.

  • Related