File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed
docs/engineering/javascript/react Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Scroll Top React HOC
2
+
3
+ This component can be used to automate scrolling to the top of a given component when the component is rendered.
4
+
5
+ A good example would be scrolling to the top of an accordion when opening the accordion.
6
+
7
+ ``` typescript
8
+ import React , { useEffect , useRef } from ' react'
9
+
10
+ /**
11
+ * The purpose of this component is to allow us to consistently scroll to the
12
+ * respective parent <tr> each time we open the containing accordion.
13
+ *
14
+ * In the example below, our target is a table rows parent.
15
+ */
16
+ export const ScrollTopWrapper: React .FC = ({ children }) => {
17
+ const { container } = useStyles ()
18
+ const ref = useRef <HTMLDivElement >(null )
19
+
20
+ useEffect (() => {
21
+ /**
22
+ * Traverse the dom tree to find the closest previous <tr /> sibling
23
+ *
24
+ * This will be the table row which triggered the <Collapse />
25
+ */
26
+ const targetElement = ref .current ?.closest (' tr' )?.previousElementSibling
27
+
28
+ /**
29
+ * To prevent further scrolling when the component unmounts, we store the
30
+ * ID of the timeout we create then clear the timeout in the cleanup.
31
+ */
32
+ const timeOutId = setTimeout (
33
+ () => targetElement ?.scrollIntoView ({ behavior: ' smooth' }),
34
+ 500 ,
35
+ )
36
+
37
+ return () => clearTimeout (timeOutId )
38
+ })
39
+
40
+ return <div ref ={ref}>{children }< / div >
41
+ }
42
+ ```
Original file line number Diff line number Diff line change 53
53
- React :
54
54
- React DevTools : engineering/javascript/react/react-devtools.md
55
55
- React setTimeout : engineering/javascript/react/react-class-timeout.md
56
+ - ScrollTopWrapper : engineering/javascript/react/scroll-top-HOC.md
56
57
- NPM :
57
58
- NVM QuickStart : engineering/javascript/npm/nvm.md
58
59
- NPM Tips & Snippets : engineering/javascript/npm/npm-tips.md
You can’t perform that action at this time.
0 commit comments