I am trying to programmatically toggle a class on an image tag inside my react application, but I can not figure out how.
let imgs = useRef();
useEffect(() => {
imgs = document.querySelectorAll('.img-intro');
}, []);
console.log(imgs);
imgs[1].classList.toggle('hide');
return (
<img ref={imgs} className='img-intro hide' src='' />
<img ref={imgs} className='img-intro hide' src='' />
<img ref={imgs} className='img-intro hide' src='' />
);
I am encountering the following error when trying to use React.useRef
on multiple image tags and when trying to use the query selector.
2
Answers
The
imgs
ref should be assigned like thisims.current = document.querySelectorAll('.img-intro');
For best practice, you should rename
imgs
toimgRefs
Take a look at useRef usage
Chao ban, can you check out this code
https://stackblitz.com/edit/react-vxfxn3?file=src%2FApp.js