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.
CodePudding user response:
It can be fixed like this:
Remove
scrollRight();
from yourhandleKeyDown
handler.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;
};
- Add the following
useEffect
to make the scroll once after the search item is added:
useEffect(() => {
scrollRight();
}, [tagSearch]);
Working Demo: