-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathAutoScrollToNewChildren.js
36 lines (32 loc) · 1.03 KB
/
AutoScrollToNewChildren.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import React, { useEffect, useState, useRef } from 'react'
/**
* A wrapper component which scrolls the first new child into view when
* the number of children increases.
*/
const AutoScrollToNewChildren = function({ children }) {
const childCount = React.Children.count(children)
const [priorChildCount, setPriorChildCount] = useState(childCount)
const firstNewChild = useRef(null)
useEffect(() => {
if (!priorChildCount) {
setPriorChildCount(childCount)
} else if (childCount > priorChildCount) {
firstNewChild.current.scrollIntoView({ behavior: 'smooth' })
setPriorChildCount(childCount)
}
}, [childCount, setPriorChildCount, priorChildCount])
return (
// wrapped in a Fragment so react-docgen recognizes this as a Component:
<>
{React.Children.map(children, (child, index) => {
return (
<>
{child}
{index === priorChildCount ? <div ref={firstNewChild} /> : null}
</>
)
})}
</>
)
}
export default AutoScrollToNewChildren