Hi i am trying to use ternary operator for multiple cases.
below is the code snippet,
const status_color_to_icon_name = {
white: 'info',
orange: 'major',
}
const default_icon_name = 'icon1';
<Icon name={status_color_to_icon_name[item.color] ?? default_icon_name} color=
{item.color} />
the above works fine. it looks for item name based on item.color if no name found in status_color_to_icon_name based on item.color it returns default_icon_name
now i have other condition if item.color is ‘red’ then i want to use custom_icon
i have tried below,
const custom_icon ='icon2';
const status_color_to_icon_name = {
white: 'info',
orange: 'major',
}
const default_icon_name = 'icon1';
<Icon name={item.color === 'red' ? custom_icon :
status_color_to_icon_name[item.color] ?? default_icon_name} color=
{item.color} />
but the above doesnt seem correct. could someone help me with this. thanks.
EDIT: fixed the typo for custom_icon_name and also this item.color could be undefined tried like so
<Icon name={(item.color && item.color === 'red') ? custom_icon :
status_color_to_icon_name[item.color] ?? default_icon_name}
/>
can we rewrite this something better.
2
Answers
Your approach is correct, but there is a small typo in your code.
You defined
custom_icon
but usedcustom_icon_name
You can simplify and improve the readability of your code by restructuring the ternary operator and using a fallback for undefined
item.color
in a more concise way:If we actually try to debug it:
So, the ternary operator:
item.color === 'red' ? custom_icon : ...
checks if the color is'red'
, and if so, logs thecustom_icon
.Fallback to
default_icon_name: status_color_to_icon_name[item.color] || default_icon_name
checks the object for the color, and if the color is not found (e.g., blue or unknown), it defaults todefault_icon_name
.