Using document.querySelector in React? Should I use refs instead? How? Using document.querySelector in React? Should I use refs instead? How? reactjs reactjs

Using document.querySelector in React? Should I use refs instead? How?


I can't answer the "should you" part of whether to use refs for this instead other than if you do, you don't need those id values unless you use them for something else.

But here's how you would:

  1. Use useRef(null) to create the ref.

    const activeSlideRef = useRef(null);
  2. Put it on the Slide that's currently active

    <Slide ref={i === activeSlide ? activeSlideRef : null} ...>
  3. In your useEffect, use the ref's current property

    useEffect(() => {    if (activeSlideRef.current) {        activeSlideRef.current.scrollIntoView({          behavior: 'smooth',          block: 'nearest',          inline: 'nearest'        });    }}, [activeSlide]);

    (I think activeSlide is a reasonable dependency for that effect. You can't use the ref, the ref itself doesn't vary...)

Live example, I've turned some of your components into divs for convenience: