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>;
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jun 11, 2019 at 13:38
\$\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>

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

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.