React scroll into view last item added in a list

What if we want to scroll to view the last element added to a React list? Or actually any array style elements?

See the below video for the full example:

We will start with this basic setup:

const App = () => {
  const [items, setItems] = useState([]);

  const handleAddClick = () => {
    setItems((items) => [
      ...items,
      {
        id: Math.random().toString(16).substr(2),
        label: "LABEL: " + Math.random().toString(16).substr(2)
      }
    ]);
  };

  return (
    <>
      <button onClick={handleAddClick}>Add list item ({items.length})</button>
      <ul>
        {items.map((i) => (
          <li key={i.id}>{i.label}</li>
        ))}
      </ul>
    </>
  );
};

What the above code will do is generate some random items and add them to a list.

However when new items are added no scroll happens.
react list with dynamic list and no automatic scroll

We have seen in a previous article how to scroll to a React element when a button is clicked, by using a combination of scrollIntoView() view and the ref hook.

The ref.current gives us access to the actual HTML element. Any element HTML element has a lastElementChild property that points to the element's last child. In the case of a list, this will point to the last element added to a list.

Therefore we can simply do something like this:

listRef.current?.lastElementChild?.scrollIntoView()

Where listRef is the reference to our list.

You can check out below the full code:

const App = ()=> {
  const listRef = useRef(null);
  const [items, setItems] = useState([]);

  useEffect(() => {          
    listRef.current?.lastElementChild?.scrollIntoView();
  }, [items]);

  const handleAddClick = () => {
      setItems((items) => [
        ...items,
        {
          id: Math.random().toString(16).substr(2),
          label: 'LABEL: ' + Math.random().toString(16).substr(2),
        },
      ]);
  };

  return (
    <>
      <ul ref={listRef}>
        {items.map((i) => (
          <li key={i.id}>{i.label}</li>
        ))}
      </ul>
      <button onClick={handleAddClick}>Add list item ({items.length})</button>
    </>
  );
}

And here is the working codepen for this example.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


One Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X