Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda