Ben Ahlander
Ben Ahlander

Reputation: 1333

How to change class name based on scroll position?

I am using reactjs and need to change the class name of a div based on scroll position. Once this div reaches the top of the page, I need to change its class. Any suggestions on how to do this?

Upvotes: 0

Views: 789

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281726

You would get the offsetTop position for your div and then compare it with scrollTop, if it satisfies your condition, you would set a state which in turn would set the className.

Sample code:

class App extends React.Component {
  state = {
    style: null
  };

  handleScroll = e => {
    if (e.target.scrollTop >= this.bbox.offsetTop) {
      this.setState({
        className: "something",
        divStyle: { backgroundColor: "orange" }
      });
    }
  };
  render() {
    return (
      <div onScroll={this.handleScroll} style={styles}>
        <Ipsum />
        <Ipsum />
        <br />
        <div
          className={this.state.className}
          style={this.state.divStyle}
          ref={ref => (this.bbox = ref)}
        >
          HelloWorld
        </div>
        <br />
        <Ipsum />
        <Ipsum />
        <Ipsum />
        <Ipsum />
        <Ipsum />
      </div>
    );
  }
}

P.S. However unlike the sample code, you need to make sure that you are not setting the state everytime, for performance reasons.

Working DEMO

Upvotes: 1

Related Questions