2
\$\begingroup\$

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, switchs 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.

Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Jun 14, 2021 at 14:36
\$\endgroup\$
1
  • \$\begingroup\$ little code. It is nice. All by Fowler )) \$\endgroup\$ Commented Jun 14, 2021 at 15:01

1 Answer 1

1
\$\begingroup\$

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.

answered Jun 14, 2021 at 16:35
\$\endgroup\$
1
  • \$\begingroup\$ Nice catch with destructuring! \$\endgroup\$ Commented Jun 14, 2021 at 18:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.