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 ?
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.