skip to Main Content

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.

browser console error

2

Answers


  1. The imgs ref should be assigned like this

    ims.current = document.querySelectorAll('.img-intro');

    For best practice, you should rename imgs to imgRefs

    let imgs = useRef();
    
    useEffect(() => {
      // assigned useRef variable
      imgs.current = document.querySelectorAll('.img-intro');
    }, []);
    
    // access to useRef variable
    console.log(imgs.current[1]);
    imgs.current[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='' />
    );
    

    Take a look at useRef usage

    Login or Signup to reply.
  2. Chao ban, can you check out this code
    https://stackblitz.com/edit/react-vxfxn3?file=src%2FApp.js

    import React from 'react';
    import './style.css';
    
    export default function App() {
      const imgs = React.useRef();
    
      React.useEffect(() => {
        imgs.current = document.querySelectorAll('.img-intro');
      }, []);
    
      return (
        <div>
          <button
            onClick={() => {
              const a = imgs.current?.[1].classList.toggle;
              console.log(a);
              debugger;
              imgs.current?.[1]?.classList?.toggle('hide');
            }}
          >
            toggle
          </button>
    
          <img
            style={{ border: '1px solid red', width: '50px', height: '50px' }}
            className="img-intro hide"
            src=""
          />
          <img
            style={{ border: '1px solid red', width: '50px', height: '50px' }}
            className="img-intro hide"
            src=""
          />
          <img
            style={{ border: '1px solid red', width: '50px', height: '50px' }}
            className="img-intro hide"
            src=""
          />
        </div>
      );
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search