Created
September 11, 2015 00:15
-
-
Save jesseditson/336524f5bee23ffece66 to your computer and use it in GitHub Desktop.
ES6 & React Sticky scroll higher-order component example
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 MyComponent from '../components/MyComponent' | |
export default class App extends React.Component { | |
render() { | |
return <MyComponent topMargin="10"/> | |
} | |
} |
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 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) |
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' | |
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