Seoyoon Park Seoyoon Park - 2 months ago 22
React JSX Question

ReactJS - Inline styling does not update upon rerendering of component

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!

Answer

Initially it works fine because you have translateY(0) and in css 0 is fine without 'px' but once you update you are trying to do translateY(35) but css expects a px value so just change to translateY(${scrolled}px)