Skip to content

Instantly share code, notes, and snippets.

@jesseditson
Created September 11, 2015 00:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jesseditson/336524f5bee23ffece66 to your computer and use it in GitHub Desktop.
Save jesseditson/336524f5bee23ffece66 to your computer and use it in GitHub Desktop.
ES6 & React Sticky scroll higher-order component example
import React from 'react'
import MyComponent from '../components/MyComponent'
export default class App extends React.Component {
render() {
return <MyComponent topMargin="10"/>
}
}
import React from 'react'
import sticky from '../protocols/sticky'
class MyComponent extends React.Component {
render() {
return (<h3>sticky, with a margin of {this.props.topMargin}</h3>)
}
}
export default sticky(MyComponent)
import React from 'react'
export default function sticky(Component) {
class StickyView extends React.Component {
constructor(props) {
super(props)
// In es6 react components, this is used instead of `getInitialState`
// the loop just is a lazy version of hand-assigning each default property to the state, without inheriting _all_ properties (some will be intended for the inheriting component).
this.state = this.state || {}
for (let k in StickyView.defaultProps) {
this.state[k] = props[k]
}
},
componentDidMount: function() {
window.addEventListener("scroll", this.onScroll, false);
},
componentWillUnmount: function() {
window.removeEventListener("scroll", this.onScroll, false);
},
onScroll: function() {
if (window.scrollY >= 100 && !this.state.sticky) {
this.setState({sticky: true});
} else if (window.scrollY < 100 && this.state.sticky) {
this.setState({sticky: false});
}
},
render() {
return <div class="sticky-container" style={{'background-color':'#f2f;'}}>
<Component {...this.props} {...this.state}/>
</div>
}
}
// Top margin here to demonstrate that sub components share props.
StickyView.defaultProps = { topMargin: 0, sticky: false }
return StickyView
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment