Skip to content

Commit 6674f61

Browse files
committed
💥 Add ScrollTopWrapper
1 parent 7f79dec commit 6674f61

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
```

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ nav:
5353
- React:
5454
- React DevTools: engineering/javascript/react/react-devtools.md
5555
- React setTimeout: engineering/javascript/react/react-class-timeout.md
56+
- ScrollTopWrapper: engineering/javascript/react/scroll-top-HOC.md
5657
- NPM:
5758
- NVM QuickStart: engineering/javascript/npm/nvm.md
5859
- NPM Tips & Snippets: engineering/javascript/npm/npm-tips.md

0 commit comments

Comments
 (0)