Sweet Alert helps your software application give fanciful and useful feedback to users after they must have performed some action.
Alerts are necessary and simple pointers that can even be created using Javascript:
alert("hello world!")
Sweet Alert can be integrated with most programming languages and libraries. But in this tutorial, we shall be implementing it in our React application.
If you are new to Sweet Alert you can get started with it here.
And for the sake of this tutorial, we are going to be making use of a variant SweetAlert2.
Let’s get started.
Create a new React application and add the following dependencies:
yarn add bootstrap
yarn add sweetalert2
import React, { Component } from "react";
class Home extends Component {
render(){
return(
<div>
</div>
)
}
}
export default Home;
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
class Home extends Component {
render(){
return(
<div className="container d-flex justify-content-center" style={{marginTop: 90}}>
<button onClick={this.showAlert} className="btn btn-primary btn-lg">
Show Alert
</button>
</div>
)
}
}
export default Home;
Notice that in our button we have function showAlert which will be fired when we click on the button.
showAlert = () => {
Swal.fire({
title: "Success",
text: "Alert successful",
icon: "success",
confirmButtonText: "OK",
});
}
import React, { Component } from "react";
import Swal from "sweetalert2";
import "bootstrap/dist/css/bootstrap.min.css";
class Home extends Component {
showAlert = () => {
Swal.fire({
title: "Success",
text: "Alert successful",
icon: "success",
confirmButtonText: "OK",
});
}
render(){
return(
<div className="container d-flex justify-content-center" style=. {{marginTop: 90}}>
<button onClick={this.showAlert} className="btn btn-primary btn-lg">Show Alert</button>
</div>
)
}
}
export default Home
Here’s the result of our code:
What if when we click on the button OK, we want to redirect our application to another page?
We’ll just modify our showAlert function as follows
showAlert = () => {
Swal.fire({
title: "Success",
text: "Alert successful",
icon: "success",
confirmButtonText: "OK",
}).then(function () {
// Redirect the user
window.location.href = "/new-page";
});
}
This is how to implement Sweet Alert in your React JS applications.
Let me know what you think in the comments!
Regardless of whether TikTok faces a U.S. ban, Instagram is wasting no time positioning itself…
Amazon Web Services (AWS) continues to enhance its customer experience by offering more flexible payment…
JavaScript, often hailed as the "language of the web," continues to dominate the programming landscape…
Amazon is accelerating efforts to reinvent Alexa as a generative AI-powered “agent” capable of performing…
SpaceX's satellite-based Starlink, which is currently unlicensed for use in India, is reportedly being utilized…
Netflix, a pioneer in the streaming industry, has always been at the forefront of adopting…