1

I make some of canvas menu on my component in react, now it's working conditionally. So I have a state:

constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    this.toggleMenu = this.toggleMenu.bind(this);
}

componentDidMount() {
    this.setState({isToggleOn: false});
}

toggleMenu() {
    this.setState(prevState => ({
        isToggleOn: !prevState.isToggleOn
    }));
}

I want to make my body css overflow:hidden when my isToggleOn state is true and when it's false I want to delete overflow:hidden from body. How can that be achieved?

Tatranskymedved
  • 4,194
  • 3
  • 21
  • 47
user3348410
  • 2,733
  • 10
  • 51
  • 85
  • Possible duplicate of [React Js conditionally applying class attributes](https://stackoverflow.com/questions/30533171/react-js-conditionally-applying-class-attributes) – Junius L Mar 14 '19 at 11:49

1 Answers1

6

You can add a componentDidUpdate lifecycle hook where you check if isToggleOn changed in the state and update the body overflow style if it did.

componentDidUpdate(prevProps, prevState) {
  if (this.state.isToggleOn !== prevState.isToggleOn) {
    document.body.style.overflow = this.state.isToggleOn ? 'hidden' : 'visible';
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • is there any benefit in putting that logic in CDU instead of in `toggleMenu`? – Giorgi Moniava Mar 14 '19 at 12:24
  • @giorgim OP is also toggling the state in CDM, so I thought it was the most straight-forward solution given that the state was updated in more than one place. – Tholle Mar 14 '19 at 12:30