Home > Net >  scroll to div using useRef in map method
scroll to div using useRef in map method

Time:07-19

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 -

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

CodePudding user response:

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.

  • Related