GA-MO / react-confirm-alert

react component confirm dialog.
https://ga-mo.github.io/react-confirm-alert/demo/
MIT License
272 stars 105 forks source link

Rerender the confirm-alert #16

Closed DanielMargolin-Taboola closed 5 years ago

DanielMargolin-Taboola commented 5 years ago

Hi!

I am using your library and it's awesome! In my project I call confirmAlert similar to the documentation:

class App extends React.Component {

  submit = () => {
    confirmAlert({
    customUI: ({ onClose }) => {
      return (
        <div className='custom-ui'>
          <h1>Are you sure?</h1>
          <p>You want to delete this file?</p>
          <button onClick={onClose}>No</button>
          <button onClick={() => {
              this.handleClickDelete()
              onClose()
          }}>Yes, Delete it!</button>
        </div>
      )
    }
   })
  };

  render() {
    return (
      <div className="container">
        <button onClick={this.submit}>Confirm dialog</button>
      </div>
    );
  }
}

But when App receives new props I want to rerender the ReactConfirmAlert.

The solution I used:

In order to update the mounted ReactConfirmAlert with the new props, I added a new exported function called updateElementReconfirm which receives properties and calls ReactDOM.render with the new properties:

export function updateElementReconfirm (properties) {
  render(<ReactConfirmAlert {...properties} />, document.getElementById('react-confirm-alert'))
}

And then, in App, I did something like:

componentDidUpdate () {
  updateElementReconfirm({
    customUI: ({ onClose }) => {
      return (
        <div className='custom-ui'>
          <h1>Are you sure?</h1>
          <p>{this.props.message}</p>
          <button onClick={onClose}>No</button>
          <button onClick={() => {
              this.handleClickDelete()
              onClose()
          }}>{this.props.buttonLabel}</button>
        </div>
       )
      }
  })
}

Here is a link to the commit

And if you find this useful I can open a pull request :)

GA-MO commented 5 years ago

@DanielMargolin-Taboola Thanks a lot for the issue. I think we should call confirmAlert() again, But we have to check if there is an old element just rerender.

function createElementReconfirm (properties) {
  // If has this DOM just rerender
  let divTarget = document.getElementById('react-confirm-alert')
  if (divTarget) {
    // Rerender
    render(<ReactConfirmAlert {...properties} />, divTarget)
    return
  }

  document.body.children[0].classList.add('react-confirm-alert-blur')
  divTarget = document.createElement('div')
  divTarget.id = 'react-confirm-alert'
  document.body.appendChild(divTarget)
  render(<ReactConfirmAlert {...properties} />, divTarget)
}

// and 

function createSVGBlurReconfirm () {
  // If has svg ignore to create the svg
  const svg = document.getElementById('react-confirm-alert-firm-svg')
  if (svg) return

  ...

}

It will be great if you make this PR :)