Home > Blockchain >  How to useRef and scrollIntoView to scroll to specific element in a mapped list in React
How to useRef and scrollIntoView to scroll to specific element in a mapped list in React

Time:02-25

I have a list of events that is scrollable on the y axis, as below:

 {events.map((event) => (
   <li
     ref={event.ref}
     key={event.id}
     >
     {event.name)
   </li>
 ))}

When clicking a button I would like the event I specify to scroll to the top of the above mapped list.

I am currently using useRef, but I am unsure how to specify the exact event I would like to scroll to the top.

For example, let's say I would like to scroll to the event with an id of 5, when clicking the button.

Here is my current code:

 const eventRef = useRef(null);
  const scrollToMyRef = () =>
    eventRef.current.scrollIntoView({
      behavior: "smooth",
      block: "end",
      inline: "nearest",
    });

   <button
     onClick={() => scrollToMyRef()}
    >
      Click me
   </button>

CodePudding user response:

I would keep track of which event.id you want to scroll to in state, and then only render a ref on the event that matches the id in state.

Working sandbox

const Example = (props) => {
  const [id, setId] = useState('1');

  const ref = useRef(null);

  const handleButtonClick = () =>
    ref.current.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
      inline: 'nearest',
    });

  return (
    <>
      <button onClick={handleButtonClick}>Click me</button>
      {events.map((event) => (
        <li ref={event.id === id ? ref : null} key={event.id}>
          {event.name})
        </li>
      ))}
    </>
  );
};
  • Related