I've encountered an issue while trying to achieve a parallax style effect for one of my components. Currently, I am transforming the inline style by setting a scroll listener once the component mounts and changing the component state upon scroll. However, the inline style does not seem to change during re-rendering even though I have checked the output of the state in the render function and seems to have correct outputs. I tried checking previous answers, but I haven't been able to correct this issue.
Currently, my setup is as follows:
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
style: {
transform: 'translateY(0)'
}
};
this.parallax = this.parallax.bind(this);
}
componentDidMount() {
window.addEventListener('scroll', this.parallax);
}
componentWillUnMount() {
window.removeEventListener('scroll', this.parallax);
}
parallax() {
function onScroll() {
let scrolled = window.pageYOffset;
this.setState({
style: {
transform: `translateY(${scrolled})`
}
});
}
if(window.pageYOffset < window.innerHeight) {
window.requestAnimationFrame(onScroll.bind(this));
}
}
render() {
return (
<div className="home-wrapper" style={this.state.style}>
</div>
);
}
}
If anyone has any suggestions I will appreciate it. Thanks!