I have been struggling with something that has always been very simple for me in vanilla JS, but is causing me issues in React. I am simply trying to run an onClick event handler on an element, but I continue to get the dreaded "Cannot read properties of null (reading 'style')"
Inside of a React Component:
function TestComponent() {
const testElement = document.querySelector('.test');
const runTest = () => {
testElement.style.display = "block";
}
return (
<div>
<div className="test" onClick={runTest}></div>
</div>
);
}
export default TestComponent;
But when I try to click the "test" component, I keep getting
Uncaught TypeError: Cannot read properties of null (reading 'style')
After some research it sounds like maybe my DOM is not fully loaded before my Script tries to run, causing the error? I found ways to mitigate this with vanilla JS (essentially, "move your script to just above the closing body tag"), but it doesn't work that way in React.
Does it seem like my problem is that it's trying to run the script too early or something else? If so, how can I tell the script on a particular component to wait until the DOM is loaded before running?
CodePudding user response:
You need to use react's API and approaches for things like that, so you have 2 different ways basically.
Using createRef hook:
function TestComponent() {
const elementRef = createRef(null);
const runTest = () => {
console.log(elementRef);
elementRef.current.style.display = "block";
elementRef.current.style.color = "red";
};
return (
<div>
<div className="test" ref={elementRef} onClick={runTest}>
test
</div>
</div>
);
}
Or using plain bindings:
function TestComponent() {
const [color, setColor] = useState("black");
const runTest = () => {
setColor("red");
};
return (
<div>
<div
className="test"
style={{
color: color
}}
onClick={runTest}
>
test
</div>
</div>
);
}