Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading