Skip to content
Advertisement

I am using UseEffect Hook, but still component is getting Uncaught TypeError: Cannot set properties of null. in react

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.

  useEffect(()=>{
    document.getElementById("address-i").onmouseover = () => {
      document.getElementById("address-instructions").style.display = "block";
    };
  
    document.getElementById("address-i").onmouseout = () => {
      document.getElementById("address-instructions").style.display = "none";
    };
  }, []);

Advertisement

Answer

you can use useRef for the same…

import "./styles.css";
import { useRef } from "react";

export default function App() {
  const h2 = useRef();
  const hideElement = (ref) => {
    ref.current.style.display = "none";
  };
  const visibleElement = (ref) => {
    ref.current.style.display = "block";
  };
  return (
    <div className="App">
      <h1
        onMouseOver={hideElement.bind(this, h2)}
        onMouseOut={visibleElement.bind(this, h2)}
      >
        Hello CodeSandbox
      </h1>
      <h2 ref={h2}>Start editing to see some magic happen!</h2>
    </div>
  );
}

You can use above code directly on codesandbox.

I hope this will help you! Happy coding…

Advertisement