patternjavascriptreactCritical
Update style of a component onScroll in React.js
Viewed 0 times
updateonscrollreactstylecomponent
Problem
I have built a component in React which is supposed to update its own style on window scroll to create a parallax effect.
The component
This doesn't work because React doesn't know that the component has changed, and therefore the component is not rerendered.
I've tried storing the value of
Any suggestion on how to do this?
The component
render method looks like this:function() {
let style = { transform: 'translateY(0px)' };
window.addEventListener('scroll', (event) => {
let scrollTop = event.srcElement.body.scrollTop,
itemTranslate = Math.min(0, scrollTop/3 - 60);
style.transform = 'translateY(' + itemTranslate + 'px)');
});
return (
);
}This doesn't work because React doesn't know that the component has changed, and therefore the component is not rerendered.
I've tried storing the value of
itemTranslate in the state of the component, and calling setState in the scroll callback. However, this makes scrolling unusable as this is terribly slow.Any suggestion on how to do this?
Solution
You should bind the listener in
Something like this:
componentDidMount, that way it's only created once. You should be able to store the style in state, the listener was probably the cause of performance issues.Something like this:
componentDidMount: function() {
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount: function() {
window.removeEventListener('scroll', this.handleScroll);
},
handleScroll: function(event) {
let scrollTop = event.srcElement.body.scrollTop,
itemTranslate = Math.min(0, scrollTop/3 - 60);
this.setState({
transform: itemTranslate
});
},Code Snippets
componentDidMount: function() {
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount: function() {
window.removeEventListener('scroll', this.handleScroll);
},
handleScroll: function(event) {
let scrollTop = event.srcElement.body.scrollTop,
itemTranslate = Math.min(0, scrollTop/3 - 60);
this.setState({
transform: itemTranslate
});
},Context
Stack Overflow Q#29725828, score: 299
Revisions (0)
No revisions yet.