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.

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

Demo

enter image description here


Source

importReact, { useState } from"react";
importSelectfrom"react-select";

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

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

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

exportdefaultApp;

Edit cocky-worker-h2sgn

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