Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
How can I make the code shorter when I want to modify a className by each props?

I want to make this code shorter especially at the [if~else if]sentence. because I want to modify a className depends on each props.

export defalut function Button(props) {

const { name, height, color, bgColor } = props;

let className = color + ' ' +bgColor+ ' w-20 rounded border border-black border-solid ';
  
if (height === 'small') {
    className += 'text-xs h-7';
} else if(height === 'medium') {
    className += 'text-base h-11'; 
} else if(height === 'large') {
    className += 'text-lg h-12'; 
}

return (
  <button className={className}>{name}</button>
)}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Use an object indexed by height string.

const classesByHeight = {
  small: 'text-xs h-7',
  medium: 'text-base h-11',
  large: 'text-lg h-12'
};
// ...
const className = `${classesByHeight[height]} ${color} ${bgColor} w-20 rounded border border-black border-solid`;

If the height might not be one of those, then alternate with the empty string too so you don't get an undefined.

const className = `${classesByHeight[height] ?? ''} ${color} ${bgColor} w-20 rounded border border-black border-solid`;
about 4 years ago · Juan Pablo Isaza Report

0

You can use switch statement to replace if else like in the following code:

switch(height) {
  case 'small':
    className += 'text-xs h-7';
    break;
  case 'medium':
    className += 'text-base h-11'; 
    break;
  case 'large':
    className += 'text-lg h-12';
    break;
  default:
    className += '';
} 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!