I am using react-select latest to create an async select ponent. I am trying to change the background color and border color of the select, once I select some value. I went through the document and tried using state.isSelected to conditionally change the background color. But no help.
When the value is selected as below, I would like to change the background color and also the border color. But nothing seems to happen. Help would be appreciated
I am using react-select latest to create an async select ponent. I am trying to change the background color and border color of the select, once I select some value. I went through the document and tried using state.isSelected to conditionally change the background color. But no help.
When the value is selected as below, I would like to change the background color and also the border color. But nothing seems to happen. Help would be appreciated
Share Improve this question edited Mar 22, 2020 at 15:02 keikai 15.2k10 gold badges55 silver badges72 bronze badges asked Mar 22, 2020 at 11:24 Brijesh PrasadBrijesh Prasad 5798 silver badges25 bronze badges 01 Answer
Reset to default 5Method
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
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;