Is there a way to turn a selection from a dropdown to a tag with the appropriate color (see the image).
ItemDisplay.jsx
JavaScript
x
29
29
1
export default function ItemDisplay() {
2
3
const colourStyles = {
4
singleValue: (provided, { data }) => ({
5
provided,
6
backgroundColor:
7
data.value === "Good"
8
? "#36B37E"
9
: data.value === "Medium"
10
? "#FF8B00"
11
: data.value === "Bad"
12
? "#FF5630"
13
: ""
14
})
15
};
16
17
return (
18
19
<Dropdown
20
style={styles.select}
21
options={TASTE}
22
defaultValue={TASTE.find((t) => t.label === item.taste)}
23
styleSelect={colourStyles}
24
/>
25
</div>
26
27
);
28
}
29
Advertisement
Answer
What you can do is having another Tag component that replace the dropdown each time you select an element:
JavaScript
1
35
35
1
export default function CustomDropdown({
2
style,
3
options,
4
styleSelect,
5
defaultValue
6
}) {
7
const [selected, setSelected] = React.useState(defaultValue);
8
const backgroundColor = styleSelect?.(selected?.label) ?? "grey";
9
10
const Tag = () => {
11
return (
12
<div style={{display: "flex", justifyContent:"space-around", padding: "0.2em",backgroundColor: backgroundColor, borderRadius: "2px", color:"white"}}>
13
{selected.label}
14
<button
15
style={{backgroundColor: "transparent", color:"white", border: "none", cursor: "pointer"}}
16
onClick={() => setSelected(null)}>x</button>
17
</div>
18
)
19
}
20
return (
21
<div style={style}>
22
{selected ?
23
<Tag />
24
:
25
<Select
26
value={selected}
27
onChange={setSelected}
28
options={options}
29
/>
30
}
31
32
</div>
33
);
34
}
35
Ideally you should create a proper file for the Tag component and pass the selected prop to the component.
Also I changed the implementation of colourStyles and made it a function that returns the proper color based on the selection:
JavaScript
1
13
13
1
const colourStyles = (selected) => {
2
switch(selected){
3
case "Good":
4
return "#36B37E";
5
case "Medium":
6
return "#FF8B00";
7
case "Bad":
8
return "#FF5630";
9
default:
10
return ""
11
}
12
};
13