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?

1

1 Answer 1

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';
  }
}
2
  • is there any benefit in putting that logic in CDU instead of in toggleMenu? Commented Mar 14, 2019 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
    Commented Mar 14, 2019 at 12:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.