MdC
MdC

Reputation: 41

Why does the onClick only work the first time?

After the first onClick the modal displays. It is then removed after when clicking outside of it. However, despite the button not being a child of the modal, its onClick fails to update this.state.changed and remove the div. Why? Codepen: https://codepen.io/Matt-dc/pen/KJYxqv

class Modal extends React.Component {
   setWrapperRef = (node) => {
      this.wrapperRef = node;
   }

componentWillMount = () => {
    document.addEventListener('mouseup', this.handleClickOutside);
}

componentDidMount = () => {
    document.addEventListener('mouseup', this.handleClickOutside);
}

handleClickOutside = (e) => {
  if (this.wrapperRef && !this.wrapperRef.contains(e.target)) {
      this.props.close()
  }
}


render() {
   if(!this.props.changed) {
      return null
 }
 return(
     <div id="modal">
        <div
            id="ref"
            style={myDiv}
            ref={this.setWrapperRef}
            >
            {this.props.children}
        </div>
    </div>
    ); 
  }
}


export default class App extends React.Component {

   constructor(props) {
   super(props);
   this.state = {
      changed: false,
   }
   this.handleChange = this.handleChange.bind(this);
}

handleChange = () => {
  this.setState({
    changed: !this.state.changed,
   });
}


render(){
  return(
     <div id="app">
        <input type="button" value="show" onClick={this.handleChange} />

        <Modal changed={this.state.changed} close={this.handleChange} />
   </div>

Upvotes: 0

Views: 110

Answers (2)

grenzbotin
grenzbotin

Reputation: 2565

It only looks like it does not close on button click, but actually it does close the modal and then change it immediately, again, because the handleChange function is fired two times.

The problem lies in your handleClickOutside logic, which that you trigger the handleChange function (passed via close props):

<Modal changed={this.state.changed} close={this.handleChange} />

The button you are clicking is outside the modal - that's why it is fired, again.

Upvotes: 0

swapnesh
swapnesh

Reputation: 26732

This is because of document.addEventListener('mouseup', this.handleClickOutside) in you Modal Component. Try by commenting -

document.addEventListener('mouseup', this.handleClickOutside) and it will work.

Also its better if you can render {this.state.changed.toString()} to get more details while debugging :)

Upvotes: 0

Related Questions