I have been working with React Select and I am just wondering why the arrow key navigation doesn't work when I try to modify option in the drop-down.
My implementation goes below.
<Select
styles={_customStyles}
isClearable={false}
isSearchable={true}
options={sitesOptions}
onChange={handleChange}
value={selectedOption}
menuIsOpen={true}
/>
and the _customStyles goes below,
const _customStyles = {
control: (base, state) => ({
...base,
boxShadow: 'none',
minWidth: '242px',
zIndex: 9999,
border: '1px solid lightgray', // default border color
'&:hover': { borderColor: 'gray' } // border style on hover
}),
option: (provided, state) => ({
...provided,
backgroundColor: state.isSelected ? '#d46514' : 'transparent',
':focus, :hover, :active, :visited': {
backgroundColor: state.isSelected ? '#d46514' : '#5a61691a'
}
})
};
If I remove the options object from _customStyles, I can able to navigate through the list in the drop-down. In another way, I can navigate but it was transparent. I don't know the currently selected item but when I hit 'Enter' the option gets selected.
Why the backgroundColor is not applying to the element? It was transparent. When I remove option, default colours would be applied and it's working fine.
Thanks in advance.
If you don't style the isFocused state then focused options will get the same styling as non-selected ones. Try something like this instead:
backgroundColor: state.isFocused || state.isSelected ? '#d46514' : 'transparent'
Anyway, I found the other way and hope it might help others.
I removed the pseudo-class declarations from the _customStyles and added them using CSS. I made use of classNamePrefix prop from react-select and added the custom class react-select as a prefix to my react-select elements.
<Select
styles={_customStyles}
isClearable={false}
isSearchable={true}
options={sitesOptions}
onChange={handleChange}
value={selectedOption}
menuIsOpen={true}
classNamePrefix="react-select"
/>
Check the classNamePrefix. And now in CSS,
.react-select__option--is-focused:not(.react-select__option--is-selected) {
background-color: rgba(90, 97, 105, 0.10196078431372549);
}
And _customStyles again for your reference.
const _customStyles = {
control: (base, state) => ({
...base,
boxShadow: 'none',
minWidth: '242px',
zIndex: 9999,
border: '1px solid lightgray', // default border color
'&:hover': { borderColor: 'gray' } // border style on hover
}),
option: (provided, state) => ({
...provided,
backgroundColor: state.isSelected ? '#d46514' : '#fff'
})
};
Now, I can able to navigate using arrow keys with the colours I required.
Note: React Select encourage you to use the new Styles API. Check this link React Select for further information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With