1
\$\begingroup\$

I have a very simple component, which should be styled differently based on the passed condition.

I wonder if there is a better approach to refactor this piece of code?

function RandomComponent({ number, condition }) {
    let classNameToUse;

    switch (condition) {
        case 'high':
            classNameToUse = 'number number--high';
            break;
        case 'medium':
            classNameToUse = 'number number--medium';
            break;
        default:
            classNameToUse = 'number';
    }

    return <div className={classNameToUse}>{number}</div>;
}
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

if you're just trying to decide between number--high number--medium or '' based on the condition variable, then just make a helper function that does that

then do return <div className={"number " + getNumberClass(condition)}}>{number}</div>

\$\endgroup\$
1
  • \$\begingroup\$ Thanks, yeah I guess the best thing to do is to extract the selection into a separate function. \$\endgroup\$
    – ummahusla
    Commented Jun 11, 2019 at 13:53

Your Answer

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

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