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

167
Visualizações
Why can't I change the value of a property of the styles object in React js , inside an event Listener after rendering

I have a jsx file :

import React from "react";
import ReactDom from "react-dom";
const styles = {
  textAlign: "center",
  color: "black"
};
ReactDom.render(
  <div>
    <h1 style={styles}>Good {wish}</h1>
  </div>,
  document.querySelector("#root")
);
document.querySelector("h1").addEventListener("click",function(){
  styles.color="salmon"; 
  console.log(styles);
});

I cannot change the styles object on click, it remains the same, "styles.color" is still "black". Why can't I modify the styles object ?

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

0

You really shouldn't be attempting to maniuplating the DOM when using react. It does that stuff for you!

Create a component

Mycomponent.jsx

import {useState} from 'react';
function myComponent(wish){
const [styles,updateStyles] = useState();

function doSomething()
{
// Change styles here
updateStyles(/*Whatever you're doing to styles*/)
}

return(
<h1 style={styles} onClick={doSomething}>Good {wish}</h1>
)
}
export default myComponent;

and in your main component

main.js

import React from "react";
import ReactDom from "react-dom";
import MyComponent from './Mycomponent.jsx';
ReactDom.render(
  <div>
    <MyComponent wish={/*String here*/}/>
  </div>,
  document.querySelector("#root")
);
});

I highly recommend when you're starting a new project to use create-react-app because it does all this boilerplate stuff for you so you can get straight into coding in react instead of setting it up yourself. Also I would recommend to familiarize yourself with the official react documentation.

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