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

102
Visualizações
how to add variable in jsx style attribute when there is already object?

I am trying to do text-align in textarea tag by writing logic with the variable name myStyle, so the logic is working but then when I made a toggle switch for dark mode and added more styling as object. Then myStyle stop working. So the question is how to add myStyle variable in style attribute when there is already a given object what is the correct format?


export default function TextForm(prop) {
  const [text, setText] = useState("Enter text here");

  const [myStyle, setMyStyle] = useState({
    textAlign:'left'
  })
  const textAlign = ()=>{
    if(myStyle.textAlign === 'left'){
      setMyStyle({
        textAlign: 'center'
      })
    }
    else if(myStyle.textAlign === 'center'){
      setMyStyle({
        textAlign:'right'
      })
    }
    else{
      setMyStyle({
        textAlign:'left'
      })
    }
  }

  return (
    <>
    <div className='container' style={{color: prop.mode==='light'?'Black':'white'}}>
        <h2>{prop.heading} </h2>
        <div className="mb-3">
        <textarea className="form-control " style={myStyle,{ backgroundColor:prop.mode==='light'?'white':'grey', color:prop.mode==='light'?'black':'white'}} value={text}  onChange= {handleOnChange}  id="myBox" rows="6"></textarea>
        </div>
        <button className="btn btn-primary mx-1" onClick={textAlign} >Change Text Align</button>
    </div>
    </>
  )
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Spread the existing object into a new one, and in that new one, list the additional properties desired.

<textarea
  className="form-control "
  style={{
    ...myStyle,
    backgroundColor:prop.mode === 'light' ? 'white' : 'grey',
    color: prop.mode === 'light' ? 'black' : 'white'
  }}
  value={text}
  onChange={handleOnChange}
  id="myBox"
  rows="6"
></textarea>

Though it'd be more elegant to toggle a CSS class on the element instead, and do this with CSS rules instead of through properties set via JS.

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