Search code examples
javascriptreactjssweetalertreact-datepicker

Prevent the display of the alert `swal` (sweetalert) after the component has loaded


The swal alert appears both when you click on the event and after the component loads. How to set the swal alert to be triggered only after clicking on the event and not after every refresh of the component.

Demo here: https://stackblitz.com/edit/react-2dmw2w

function Event({ event }) {

  swal({
    title: event.title,
    text: `${event.description} ${event.id}`,
    /*icon: "info",*/
    buttons: true,
    dangerMode: true,
  })
  .then((willDelete) => {
    if (willDelete) {
      swal("Poof! Your imaginary file has been deleted!", {
        icon: "success",
      });
    } else {
      swal("Your imaginary file is safe!");
    }
  });

///////

  <Calendar
    events={this.state.events}
    startAccessor="start"
    endAccessor="end"
    defaultDate={moment().toDate()}
    localizer={localizer}
    components={{
      event: Event
    }}
  />

Solution

  • I made some modifications to your code, applied ES6 (for best practices) and modified a couple of variables (Event with the capital E is a reserved word i think)

    https://stackblitz.com/edit/react-gd4kqm

    but in order to achiv what you want what I did is call SWAL only when you click the event in the calendar I did this by seperating it in two functions, if you have any questions please ask.

    list of reserved words in JS:

    https://www.w3schools.com/JS/js_reserved.asp