• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

135
Views
How to useRef and scrollIntoView to scroll to specific element in a mapped list in React

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>
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
      ))}
    </>
  );
};
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error