using shouldComponentUpdate instead of getSnapshotBeforeUpdate
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
Hi, I'm struggling a little with the new lifecycles. I have this component which passes down a style which will lock the scrollbar on the window without shifting content when applied on my root App element.
interface ScrollLockProps {
locked: boolean,
children: (style?: CSSProperties) => React.ReactNode
}
export class ScrollLock extends React.Component<ScrollLockProps> {
private scrollY = 0
public shouldComponentUpdate() {
if (!this.props.locked) {
this.scrollY = window.scrollY
}
return true
}
public componentDidUpdate() {
if (!this.props.locked) {
window.scrollTo(0, this.scrollY)
}
}
public render() {
const { locked, children } = this.props
const style: CSSProperties | undefined = locked ? {
position: "fixed",
left: "0px",
right: "0px",
top: `-${this.scrollY}px`,
} : undefined
return children(style)
}
}
The problem is I have to use shouldComponentUpdate to retrieve the scroll position, and this feels wrong to me as this lifecycle surely should only return a boolean and not have any side effects?
I can't use getSnapshotBeforeUpdate because render is called before it, which means the resulting style will be incorrect.
And of course I cannot use componentWillReceiveProps because it is deprecated.
What is the correct way to go about this?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue provides an inline TypeScript ScrollLock component rather than naming repository files or tests. Start by reviewing the React lifecycle documentation for shouldComponentUpdate, getSnapshotBeforeUpdate, and componentDidUpdate; done means establishing and documenting the correct lifecycle approach for this scroll-locking case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react, typescript
- Domain
- documentation, frontend
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100