Last active
January 16, 2017 02:11
-
-
Save mjackson/083624acf6f78fb4d8cd to your computer and use it in GitHub Desktop.
Make window.scrollTo declarative using a <WindowScrollTo> React component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import warning from 'warning' | |
const { number, object } = React.PropTypes | |
const WindowScrollTo = React.createClass({ | |
contextTypes: { | |
windowScrollTo: object | |
}, | |
childContextTypes: { | |
windowScrollTo: object.isRequired | |
}, | |
getChildContext() { | |
return { | |
windowScrollTo: this | |
} | |
}, | |
propTypes: { | |
x: number, | |
y: number | |
}, | |
updateScrollPosition() { | |
let { x, y } = this.props | |
if (typeof x !== 'number') { | |
if (typeof y !== 'number') | |
return // Nothing to do | |
x = window.scrollX // Preserve existing window.scrollX | |
} | |
if (typeof y !== 'number') | |
y = window.scrollY // Preserve existing window.scrollY | |
window.scrollTo(x, y) | |
}, | |
componentWillMount() { | |
warning( | |
this.context.windowScrollTo == null, | |
'You should not render more than one <WindowScrollTo> in a tree; ' + | |
'they will most likely conflict' | |
) | |
}, | |
componentDidMount() { | |
this.updateScrollPosition() | |
}, | |
componentDidUpdate(prevProps) { | |
if (prevProps.x !== this.props.x || prevProps.y !== this.props.y) | |
this.updateScrollPosition() | |
}, | |
render() { | |
return null | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually, without touching the original, you could even do this: