2

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>

1 Answer 1

5

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>
      ))}
    </>
  );
};
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Benjamin! How would I pass A specific event.id on click? For example if I wanted to pass event.id 5?
You can initialize useState with the id 5, const [id, setId] = useState(5); Or call setId(5) in an event callback. What event would you like to use to update the id? Maybe a button click? Or form input?
Awesome, thank you. I just had a go with the sandbox and saw how you have implemented it there. Appreciate your help!
@adherb you can change the block argument in scrollIntoView to block: 'start' instead of end. I have updated the answer and the code sandbox.
I was getting an error when I would select values that didn't match the event.id, to fix this I added If (!ref.current) { return } else { ref.current.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest', });}. I can't update the answer as the suggested edit queue is full.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.