React scroll into view last item added in a list

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!

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.

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!


Leave a Reply

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

Home Screencasts Best of Newsletter Search X

Neural Networks for JavaScript developers
Presale - 15$ free coupon

Hi friend! Before you go, just wanted to let you know that in March 2023 I will be launching the TensorFlow.Js by Example course.

This course will include basic concepts of AI and Neural Networks done with TensorFlowJs such as:

  • Working with datasets
  • Visualizing training
  • Deep Neural Networks in JavaScript
  • Reinforcement Learning
  • Convolutional neural networks
  • and much more ...

Also, there will be a lot of examples as:

  • Object detection
  • Natural language processing
  • Face and voice recognition
  • Gaming AI

Join now the waiting list and get a 15$ coupon off the launching price!

X