2

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.

Kuldeep Bhimte
  • 961
  • 1
  • 10
  • 25

2 Answers2

5

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>}
lecstor
  • 5,619
  • 21
  • 27
  • I need to handle the `componentDidMount` in the `Modal` component. The `Content` is just some `node` to be rendered. Please see the updated question – Kuldeep Bhimte Mar 14 '19 at 05:31
0

The following statement is incorrect:

const display = show ? 'block' : 'none';

It should be:

const display = this.state.show ? 'block' : 'none';

For there is no show in scope of render, you want to get the value of show stored in state, don't you?

Peter
  • 10,492
  • 21
  • 82
  • 132