After importing the files into your application,you can call the swal
function(make sure it's called after the DOM has loaded!)
swal ( );
If you pass two arguments, the first one will be the modal's title,and the second one its text.
swal( );
And with a third argument,you can add an icon to your alert!There are 4 predefined ones:"warning"
,"error"
,"success"
and "info"
.
swal( );
The last example can also be rewritten using an object as the only parameter:
swal({
title:
,text:
,icon:
,});
With this format,we can specify many more options to customize our alert. For example we can change the text
on the confirm button to "Aww yiss!"
:
swal({
title:
,text:
,icon:
,button:
,});
You can even combine the first syntax with the second one,which might save you some typing:
swal({
title:
,{button:
,});
SweetAlert uses promises to keep track of how the user interacts with the alert.
If the user clicks the confirm button,the promise resolves to true
. If the alert is dismissed(by clicking outside of it),the promise resolves to null
.
swal( )
.then((value) =>{
.swall( );
});
This comes in handy if you want to warn the user before they perform a dangerous action. We can make our alert even better by setting some more options:
-
-
icon
can be set to the predefined"warning"
to show a nice warning icon. -
- By setting
buttons
(plural) totrue
,SweetAlert will show a cancel button in addition to the default confirm button. -
- By setting
dangerMode
totrue
,the focus will automatically be set on the cancel button instead of the confirm button,and the confirm button will be red instead of blue to emphasize the dangerous action.
swal({
title:
,text:
,icon:
,button:
,dangerMode:
,})
.then(willDelete) =>{
(willDelete){
swal( ,{
icon:
,});
}
{swal( );
}
});
Customizing buttons
So what if you need morethan just a cancel and a confirm button? Don't worry, SweetAlert's got you covered!
By specifying an object for buttons
,you can set exactly as many buttons as you like,and specify the value
that they resolve to when they're clicked!
In the example below, we set 3 buttons:
-
-
cancel
, which by default resolves tonull
and has a custom"Run away!"
text. -
-
catch
, which will resolve to thevalue
we've specified("catch"
) and has the custom text"Throw Pokéball!"
. -
-
defeat
. Here,we specifytrue
to let SweetAlert set some default configurations for the button. In this case,
it will set thetext
to"Defeat"
(capitalized) and the resolved value todefeat
. Had we set thecancel
button totrue
,it would still resolve tonull
as expected.
swal( ,{
buttons:{
cancel:
,catch:{
text:
,value:
,catch:},
defeat:
,},
})
.then((value) =>{
(value){
swal( );
swal( );
swal( );
}
});