4

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!

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Oh of course! This minor bug kept me stumped for quite a while. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.