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

Time:09-11

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: enter image description here enter image description here

CodePudding user response:

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)

  • Related