2

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>
  );
}

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I finally figured it out thanks to this answer, similar to yours: stackoverflow.com/a/62054403/1100107 Do you know how to do with multiple selections? I just have to pass an array to the selected option?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.