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

scroll to div using useRef in map method

i am using useRef to scroll to specific div but it is not working in map method’s case (probably because of id) , so can anyone tell me how to provide id. it is taking last element in map method right now.
this is element to which i want to scroll to.

  {allMessages?.map((message) => (
            <div 
              key={message.data.id}
              ref={filterRef}>
              <div>
                <p>{message.data.text}</p>
              </div>
            </div>
          ))}

this is filtered data in which i am getting filtered messages and clicks on specific div.

{filteredMsg?.map((item) => (
                  <li 
                    onClick={() => goToFilterData(item.data.id)}
                    key={item.data.id}
                  >
                    {item.data.text}
                  </li>
                ))}

this is what i have done with useRef yet –

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

 const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop);
  const goToFilterData = (id) => {
    scrollToRef(filterRef);
  };

>Solution :

Just pass an id to every element that maybe should scroll into the view.

{allMessages?.map((message) => (
    // the element you want to scroll to
    <div id={`message_${message.someUniqueIdentifier}`} />
))}

Pass the identifier to the scroll function.

{filteredMsg?.map((item) => (
   <li onClick={() => goToFilterData(item.data.someUniqueIdentifier)}>
       {item.data.text}
   </li>
))}

Query the element and make it scroll into the view.

const goToFilterData = (uniqueIdentifier) => {
  const element = document.getElementById('message_' + uniqueIdentifier);
  element.scrollIntoView()
};

Note: ofc you could handle this with a lot of single refs and pass them, but this should just work fine.

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