I want to show the battery icon given the status
provided in props. I am trying to keep it simple but without writing too much code, i.e.: . if ... else
, switch
s statements...
Below code snippet works but it kinda looks forced, not sure.
import {
TiBatteryLow,
TiBatteryMid,
TiBatteryHigh,
TiBatteryFull
} from 'react-icons/ti'
const battery = {
low: {
color: "text-red-500",
icon: TiBatteryLow
},
mid: {
color: "text-yellow-400",
icon: TiBatteryMid
},
high: {
color: "text-green-400",
icon: TiBatteryHigh
},
full: {
color: "text-green-600",
icon: TiBatteryFull
}
};
export default function BalanceIndicator({status}) {
let Balance = battery[status].icon;
return (
<div className="text-sm flex items-center">
<i className={`mr-3 text-2xl ${battery[status].color}`}><Balance /></i>
</div>
)
}
Is there a better way to do this? Perhaps conditional rendering?
PS: In title, by condition I mean the value of status
.
-
\$\begingroup\$ little code. It is nice. All by Fowler )) \$\endgroup\$Kostiantyn Okhotnyk– Kostiantyn Okhotnyk2021年06月14日 15:01:40 +00:00Commented Jun 14, 2021 at 15:01
1 Answer 1
Prefer const
over let
The variable Balance
is declared with let
.
let Balance = battery[status].icon;
It can be declared with const
instead, since it is only assigned once. This can help avoid accidental re-assignment and other bugs.
Reducing lookups
let Balance = battery[status].icon; return ( <div className="text-sm flex items-center"> <i className={`mr-3 text-2xl ${battery[status].color}`}><Balance /></i> </div> )
With this approach the icon is stored in Balance
yet the color needs to be looked up again. The icon and color could be stored in variables after a single look-up with destructuring assignment.
const {icon, color} = battery[status];
return (
<div className="text-sm flex items-center">
<i className={`mr-3 text-2xl color}`}><icon /></i>
</div>
)
This makes the line containing the markup shorter, which improves readability.
Error handling
What happens if status
does not correspond to a key in battery
? Perhaps it is unlikely but as code grows over time the likelihood could grow. The code should handle this scenario - perhaps with an error message or exception thrown.
-
\$\begingroup\$ Nice catch with destructuring! \$\endgroup\$Nestor– Nestor2021年06月14日 18:55:21 +00:00Commented Jun 14, 2021 at 18:55