Felipe Cristiano
Felipe Cristiano

Reputation: 301

useRef to scroll horizontally don't work for a dynamic element

I have a search field that adds tags to the left side, which after a certain number of tags added it shows overflow-x. I need that after adding a new tag, it scrolls to the right, showing the last searched tag.

The code I made uses the useRef associated with the parent element, so that after inserting a new tag it calls a function that makes the scroll.

The problem is that for some reason, regardless of the value I put in pixels for the scroll, it always reaches the penultimate element, it never reaches the end.

I believe that when he activates the scroll the last element is not yet ready in the useRef, so the penultimate element would be the last one at the moment, but I still haven't found a way to get around this.

My code: https://codesandbox.io/s/nextjs-10-tailwind-2-0-forked-wergkg?file=/pages/index.js

some predefined tags have already been added so that the overflow is already visible enter image description here enter image description here

Upvotes: 1

Views: 985

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13245

It can be fixed like this:

  1. Remove scrollRight(); from your handleKeyDown handler.

  2. Update scrollRight as below which will get the current width of scroll area instead fixed 600 pixels:

  const scrollRight = () => {
    scrollElement.current.scrollLeft += scrollElement.current.scrollWidth;
  };
  1. Add the following useEffect to make the scroll once after the search item is added:
  useEffect(() => {
    scrollRight();
  }, [tagSearch]);

Working Demo:

Edit NextJS 10 + Tailwind 2.0 (forked)

Upvotes: 3

Related Questions