I have to give a hover effect to a certain element that has an id “address-instructions”. I have used UseEffect so that it is only accessed after being rendered, but I still get Uncaught TypeError: Cannot set properties of null (setting ‘onmouseover’) , which indicates that the component is not rendering. Please help. Thank you in advance.
JavaScript
x
10
10
1
useEffect(()=>{
2
document.getElementById("address-i").onmouseover = () => {
3
document.getElementById("address-instructions").style.display = "block";
4
};
5
6
document.getElementById("address-i").onmouseout = () => {
7
document.getElementById("address-instructions").style.display = "none";
8
};
9
}, []);
10
Advertisement
Answer
you can use useRef for the same…
JavaScript
1
24
24
1
import "./styles.css";
2
import { useRef } from "react";
3
4
export default function App() {
5
const h2 = useRef();
6
const hideElement = (ref) => {
7
ref.current.style.display = "none";
8
};
9
const visibleElement = (ref) => {
10
ref.current.style.display = "block";
11
};
12
return (
13
<div className="App">
14
<h1
15
onMouseOver={hideElement.bind(this, h2)}
16
onMouseOut={visibleElement.bind(this, h2)}
17
>
18
Hello CodeSandbox
19
</h1>
20
<h2 ref={h2}>Start editing to see some magic happen!</h2>
21
</div>
22
);
23
}
24
You can use above code directly on codesandbox.
I hope this will help you! Happy coding…