Home > Net >  How can I make the code shorter when I want to modify a className by each props?
How can I make the code shorter when I want to modify a className by each props?

Time:03-29

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>
)}

CodePudding user response:

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`;

CodePudding user response:

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  = '';
} 
  • Related