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

238
Visualizações
React adding conditional styling (&&)

the same newbie here. I have the code which working as intended, all I want to do is add && with state variable (boolean) to make a text have line-through decoration while clicked (using crossedItemOnClick)

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function Para(props) {
    const {id, className, info, state} = props;
    

    return (
        <p onClick={props.crossedItemOnClick} id={id} className={className} style={{textDecorationLine: 'line-through'}}>{info}</p>
    )
}

export default Para;

My whole page disappears if I change it to:

        <p onClick={props.crossedItemOnClick} id={id} className={className} style={state && {textDecorationLine: 'line-through'}}>{info}</p>

I'd love to know what I'm doing wrong and why the page completely disappears. And of course explanation to learn if you'd be kind to. Much thanks!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

style attribute takes object as value in react. Correct way will be:

<p onClick={props.crossedItemOnClick} id={id} className={className} style={state ? {textDecorationLine: 'line-through'}:{}}>{info}</p>

assuming you have to apply the style when state is true.

about 4 years ago · Juan Pablo Isaza Relatório

0

That is because style prop expect object of type CSSProperties, and in case when your condition is false you will end up with something like style={false} which will cause your app to crash since you provided HTML element with invalid styling.

Easiest solution is to just rewrite that part to style={state ? {...someStyle} : {}}

about 4 years ago · Juan Pablo Isaza Relatório

0

Your approach is mostly correct, however, your condition should be applied on the style property directly like this if you want to use &&

style={{textDecorationLine: state && 'line-through'}}
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