Search code examples
reactjsreact-lifecycle

ComponentDidMount function is called when I have `display: none`


I am conditionally rendering a modal component based on the display property.

I need to implement toggle the body scroll functionality on component show/hide.

See below implementation,

Demo component

<button onClick={()=> this.setState({ show: true })}>Show modal</button>
<Modal show={show} containerStyle={containerStyle} position={position} handleClickOutside={()=> this.setState({ show: false })} >
  <Content />
</Modal>

Modal component

componentDidMount() {
  disableBodyScroll(this.state.defaultMargin);
}

componentWillUnmount() {
  enableBodyScroll(this.state.defaultMargin);
}

render() {
  const { show } = this.props;
  const display = show ? 'block' : 'none';
  return (
    <div onClick={ handleClickOutside } className={ styles[ 'modal'] } style={ { display } }>
      {children}
    </div>
  );
}

But the issues is the componentDidMount function is called before the Modal is shown. I want it to be called after the Modal is shown

And componentWillUnmount should be called when the Modal is hidden.


Solution

  • Your display style will not prevent the component from rendering, in fact it has to render for the display style to even come into play.

    Use your state to directly control the rendering..

    <button onClick={()=> this.setState({ show: true })}>Show modal</button>
    {this.state.show && <Modal show={show} containerStyle={containerStyle} position={position} handleClickOutside={()=> this.setState({ show: false })} >
      <Content />
    </Modal>}