Search code examples
reactjsref

React using refs to scroll to when selecting from a dropdown


Ok, I am trying to create a dropdown and when selecting an item, the page should scroll to a specific section (ref).

I have several divs with the same ref (as I have more than 30 divs that require a ref).

const SettingView = () => {
    const selectedItem = "el2"; // This is temporarily as it will be the item from a dropdown
    const ref = useRef<HTMLDivElement[]>([]);
    const filterRef = (el: HTMLDivElement) => ref.current.push(el);

    return (
        <>
            for (let item of sortedRows) {
                <div ref={filterRef} id={item.some.name}>{item.text}</div>
            }
        </>
    )
}

export default SettingView;

So on a button click it should find the div ref that has the id from the selectedItem and scroll to it.

How would I do that?


Solution

  • https://stackblitz.com/edit/stackblitz-starters-tuw9cm?file=src%2FApp.tsx

    import { FC, useEffect, useRef, useState } from 'react';
    
    const Div = ({ text, isActive }) => {
      const ref = useRef<any>();
      useEffect(() => {
        if (isActive) {
          ref.current.scrollIntoView({ behavior: 'smooth' });
        }
      }, [isActive]);
      return (
        <div
          ref={ref}
          style={{
            background: isActive ? '#006699' : '#dddddd',
            height: '200px',
            margin: '10px',
          }}
        >
          {text}
        </div>
      );
    };
    
    export const App: FC<{}> = () => {
      const data = [1, 2, 3, 4, 5, 6, 7];
      const [activei, setActivei] = useState(5);
      return (
        <div>
          <div>
            {data.map((item) => (
              <div
                onClick={() => {
                  setActivei(item);
                }}
                key={item}
              >
                {' '}
                {item}{' '}
              </div>
            ))}
          </div>
          {data.map((item, index) => (
            <Div isActive={item === activei} text={item} key={item} />
          ))}
        </div>
      );
    };