Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda