Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!