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.

\$\endgroup\$
1

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.

\$\endgroup\$
1
  • \$\begingroup\$ Nice catch with destructuring! \$\endgroup\$
    – Nestor
    Jun 14, 2021 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.