5

I have this code that I call in button click to scroll to the bottom of a page:

const el = useRef<HTMLDivElement>(null);

const ScrollToBottom = () => {
    if (el.current !== null)
        el!.current!.scrollIntoView({ block: 'end', behavior: 'smooth' });
}

This helps me scroll to the element that has the el reference, for example:

<div id={'el'} ref={el}></div>

But, I want to scroll to the last element added or updated, which is not necessarily always at the end of the page. With the approach I am using now, I do not think it is possible. This is because I would need to remove all possible ref={el} attributes from other dom elements, and add it to the dynamic component recently added. I do not know if this is possible.

I wonder if there is a way to achieve this?

renakre
  • 8,001
  • 5
  • 46
  • 99
  • You can keep track of last updated or added element in a variable and use that in your `scrollToBottom` function – Code Maniac Jul 14 '19 at 16:41
  • @CodeManiac thanks for the reply! In that case, then I do not have to define `el`? Each time should I define a new ref with `useRef()`? I would appreciated it if you can provide a bit more details. – renakre Jul 14 '19 at 16:46
  • you can use `componentDidUpdate` lifecycle method to decide scrollIntoView depending upon insertion of element. I think `useEffect` would be good choice to implement lifecycle using hooks so that it will cover `componentDidUpdate`, `componentDidMount` in one `useEffect` – AviatorX Jul 14 '19 at 16:46
  • @AviatorX thanks for the ideas. I am not sure how `el!.current!.scrollIntoView()` should change in that case? How to address a specific element instead of using `el.current`? – renakre Jul 14 '19 at 16:51
  • 1
    In past I got this issue that time I created 2 classes `foucs` and `nonfoucs` so whenever I was adding element in list I was changing it's class to `focus` and other element to `nonfocus` to do this I kept track of last `focus` class element using it's `index`.`focus` and `nonfocus` both are custom `css classes` I would like to know if anyone has different approach – AviatorX Jul 14 '19 at 17:05
  • Can you create a stackblitz/codesandbox demo of your code? – Munim Munna Jul 17 '19 at 11:57
  • Yes a sandbox will help to solve the problem – Tarun Lalwani Jul 17 '19 at 12:04
  • what about height of screen? – Deepankar Singh Jul 17 '19 at 13:37
  • You can follow this link, https://stackoverflow.com/questions/37620694/how-to-scroll-to-bottom-in-react – Mahesh Joshi Jul 17 '19 at 19:09

1 Answers1

9

This may not be exactly what you want, but you could move the scrollIntoView logic into the child component and run it on mount (via componentDidMount or useEffect). It would look something like this: https://codesandbox.io/s/react-scroll-into-view-jhmuw

Simon Ingeson
  • 951
  • 7
  • 10