Search code examples
reactjsgetelementbyid

getElementById but unique for each component


I have reusable component on which I need to access its 'id' for scrolling:

var slider = document.getElementById('slider');
slider.scrollLeft = slider.scrollLeft - (3);

The Id is declared:

<div
    id='slider'
    className="scroll-smooth"
>

I know this is wrong and it obviously fails whenever more than one such component is used, as only the the first component's slider interaction takes place. How can I create a 'unique' Id (or something else) to make the id's truly unique to each object?


Solution

  • useRef, instead of getElementById

    import { useRef } from 'react';
    
    const sliderRef = useRef(null);
    sliderRef.current.scrollLeft = sliderRef.current.scrollLeft - (3);
    
    <div
        ref={sliderRef}
        className="scroll-smooth"
    ></div>