Scroll to element and leave it in the center on load using React

Let's assume that we are rendering a group of elements, and we want to scroll to a certain block and display it in the center of the page using React.

For example, let's assume that we want to render 8 elements and scroll to the 5th element:

import React, { useEffect, useRef } from 'react';

const scrollToCenter = () => {
    const ref      = useRef();
    const elems    = Array(8).fill(null);
    const scrollTo = 5;
    useEffect( () => {
            ref.current.scrollIntoView({behavior: 'smooth', block: 'center'});
    }, [ref.current]);
    return (
        <div className = 'GroupOfElems'>
            { (e, i) => 
                <div key = {i} ref = {i === scrollTo ? ref : null}>Hi</div>

export default scrollToCenter;

We are creating a reference to the element to scroll. After the reference is created, we are calling the scrollIntoView function.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.