this is the options and formatOptionLabel function
const brandOptions = films.map((film) => ({
value: film.brand,
label: film.brand,
}))
const formatOptionLabel = ({ value, label, isSelected }) => (
<div style={{ display: 'flex', alignItems: 'center' }}>
{isSelected ? null : (
<img
src={films.find((film) => film.brand === value)?.brandpic}
alt={value}
style={{ marginRight: '8px', width: '20px', height: '20px' }}
/>
)}
{label}
</div>
)
this is the dropdown
<ReactSelect
value={brandOptions.find((option) => option.value === selectedBrand)}
onChange={handleBrandChange}
options={brandOptions}
placeholder="choose the brand"
formatOptionLabel={formatOptionLabel}
className="bg-white ml-5 rounded-[40px] border-[#EBEBEB] shadow-sm w-[278px]"
/>
the options have image along with the brand name. but the problem is, when i click to choose the option, i want only the brand name display in the control. this code give me both the image and the brand name.
const formatOptionLabel = ({ value, label, isSelected }) => (
<div style={{ display: 'flex', alignItems: 'center' }}>
{isSelected ? null : (
<img
src={films.find((film) => film.brand === value)?.brandpic}
alt={value}
style={{ marginRight: '8px', width: '20px', height: '20px' }}
/>
)}
{label}
</div>
)
the {isSelected ? null : ( … part seems to have no effect
2
Answers
formatOptionLabel
arrow function checks the context to determine whether the option is being displayed in the dropdown menu or in the control. If the option is in the dropdown menu, it includes the image. If the option is in the control that means it has been selected then it only displays the label.If you wanna play around with sample code.
I had the same requirements and created my own component, have a look and let me know if it works for you as well: