How to create alert box in react js?
March 20, 2023Hi Friends π,
Welcome To aGuideHub!
To create an alert box in React js, you can use the alert function. When you call the alert function. It will show an alert box on the web page.
Today, I am going to show you, how to create alert box in react js.
Table of contents
- Create a show alert function..
- Create the Alert Box.
Letβs start with the first step.
Step 1: Create a show alert function.
In the show alert function, I will call the alert method simple messages.
function MyComponent() {
function showAlert() {
alert('This is an alert message!');
}
}
Step 2: Call show alert function.
Once you have created the component the alert function. You have to call the show alert
function onclick
of a button. You can attach this using the button onclick
event.
<div>
<button onClick={showAlert}>Click me to show alert</button>
</div>
ReactJS create alert box example.
The below code is an example of The component presents a button with an onclick
event that triggers a showalert
function, which displays an alert message
when the button is clicked.
App.js
import React from 'react';
function MyComponent() {
function showAlert() {
alert('This is an alert message!');
}
return (
<div>
<button onClick={showAlert}>Click me to show alert</button>
</div>
);
}
Check the output of the above code example.
Here, we are provided code sandbox links for the above program create alert box in React js. Then you can use whenever you went and do the changes as per your requirements.
All the best π