after learning javascript, I started to learn React and I'm not quite sure how DOM manipulation works in React, for example, I want to change the background colour in React, is it similar to Javascript or it's totally something else?
const onClick = () =>{
document.body.style.backgroundColor = 'Dodgerblue';
}
return (
<div>
<button onClick={onClick}>Change background Color</button>
</div>
)
}```
CodePudding user response:
Of course it will because react is based on JavaScript and html so this should work fine
CodePudding user response:
While your case scenario is working fine because you are selecting an element inside a function, the issue that can happen in React is if you try to select an element that is about to be rendered, (but isn't yet rendered) will return null
value because the selector method won't return any element/node.
Example code:
...
const selectText = document.getElementById("testDOM");
const faultyFunction = () => {
selectText.style.color = "red";
} //Calling this function throws TypeError: Cannot read properties of null (reading 'style')
const onClick = () =>{
const selectText = document.getElementById("testDOM");
selectText.style.color = "red";
} //This works as expected,
//as the function is selecting an element once the DOM has been rendered
return (
<div>
<button onClick={onClick}>Change Text Color</button>
<br/>
<button onClick={faultyFunction}>Faulty Button</button>
<p id="testDOM">Random Text</p>
</div>
)
...