Skip to content Skip to sidebar Skip to footer

How To Change React-select Options Styles When Select

I am using react-select latest to create an async select component. I am trying to change the background color and border color of the select, once I select some value. I went thro

Solution 1:

Method

Refer to document: react-select customize styles

You can override the default provided styles in different domains.

In this case, the base control would be good enough.

const customStyles = stateValue => ({
  control: (provided, state) => ({
    ...provided,
    backgroundColor: stateValue ? "gray" : "white"
  })
});

Demo

enter image description here


Source

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

const options = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

const customStyles = value => ({
  control: (provided, state) => ({
    ...provided,
    alignItems: "baseline",
    backgroundColor: value ? "gray" : "white"
  })
});

const App = () => {
  const [selected, setSelected] = useState("");
  const onChange = e => {
    setSelected(e.value);
  };
  const onClickButton = () => {
    setSelected("");
  };
  const displayItem = selected => {
    const item = options.find(x => x.value === selected);
    return item ? item : { value: "", label: "" };
  };
  return (
    <>
      <Select
        options={options}
        styles={customStyles(selected)}
        onChange={onChange}
        value={displayItem(selected)}
      />
      <button onClick={onClickButton}> Clear Selection </button>
    </>
  );
};

export default App;

Edit cocky-worker-h2sgn


Post a Comment for "How To Change React-select Options Styles When Select"