Issue
In React.js i want to implement the background color to a div element using useRef() hook but it doesn't work.
const cssNav = useRef()
useEffect(() => {
window.scrollY > 0 ? cssNav.style.backgroundColor = "white" : ""
}, [])
<div ref={cssNav}> </div>
Solution
- The DOM element can be accessed by using cssNav.current .
- Generally you should pass the null as the initial value(to indicate no value) to the useRef() hook when manipulating DOM.
Updated Code -
const cssNav = useRef(null);
useEffect(() => {
window.scrollY > 0 ? cssNav.current.style.backgroundColor = "white" : ""
}, []);
<div ref={cssNav}> </div>
Answered By - Sagar Sharma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.