Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda