1

I am trying to change toolbar background color as #fff color when body scrolled.Otherwise it will be transparent.

Here is sample toolbar component:

export default class ToolBar extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      scrolled:false
    }
  }
  render() {
    const { children, className,scrolled, ...other } = this.props
    return (
      <nav style={{backgroundColor:this.state.scrolled?'#fff':'transparent'}}>
        {children}
      </nav>
    )
  }
}

How can we do this with react?

tcetin
  • 979
  • 1
  • 21
  • 48
  • Does this answer your question? [Update style of a component onScroll in React.js](https://stackoverflow.com/questions/29725828/update-style-of-a-component-onscroll-in-react-js) –  Dec 03 '19 at 00:19
  • No its about effect. But I try for background color. – tcetin Dec 03 '19 at 10:53
  • The duplicate shows how to attach an `onscroll` listener and use it to change state, which is exactly what you need to solve this. –  Dec 03 '19 at 10:56

1 Answers1

1

Just add an event listener to window object.

componentDidMount() {
   window.addEventListener('scroll', this.checkScroll);
}

checkScroll = () => {
   this.setState({ scrolled: window.scrollY > 0 });
};

Note: You would probably also need some debounce to avoid rapid and multiple set states.

And remember to disconnect the listener on component destroy.

componentWillUnmount() {
   window.removeEventListener('scroll', this.checkScroll);
}
kind user
  • 40,029
  • 7
  • 67
  • 77