Alert component in React JS

React is an open-source JavaScript library for building user interfaces, usually for single-page and mobile applications. A user interface in React is built around components, each of which is a Javascript function defined by the user.

The Alert component in React.js serves as an important element for providing feedback or conveying important information to users within a web application. Alerts are prominently used to notify users about successful actions, errors, and warnings or to prompt certain actions. In React JS, there is a default alert that can be easily generated using the following:

alert('Done')

However, these default alerts appear at the top of the screen and are not visually appealing. This is why we seldom see them in the web and mobile applications we use. Generally, the alerts we encounter in web applications appear on the screen, like the one in the section below.

Expected results

Click “Run” to execute the example. Enter any text in the textbox and click “Send.” An alert will appear on the screen to confirm that your message has been sent.

Step-by-step method

In this example, we’ll create the alert component from the example above for the success condition by using the following steps:

Step 1: Create an Alert component

We’ll create a container that will show the content of the alert. In this case, the alert container will show the “Action Successful!” text. After this, we’ll create a button that triggers a window reload on click.

export default function AlertComponent() {
function handleOKButton()
{
window.location.reload();
}
return (
<div className="alertContainer">
<div className="alertBoxAppearence">
<h3 className='alertHeading'>Action Successful!</h3>
<FaCheck id='alertIcon'/>
<button className="alertButton"
onClick={(e)=>handleOKButton()}>OK</button>
</div>
</div>
)
}

Step 2: Render the Alert component

It’s time to render the Alert component when a success condition occurs. In this example, an alert “Action successful!” appears on the screen when some data is sent. No alert will be generated if no data is sent. To incorporate this functionality, we’ll create a text box using the <input></input> tag.

<input
type="text"
placeholder="Enter text..."
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>

As the alert has to appear when some data is sent, we’ll create a “Send” button. This button will be handled using a constant function handleSendClick().

import Alerts from './components/Alerts'
const [inputValue, setInputValue] = useState('');
const [showAlert, setShowAlert] = useState(false);
const handleSendClick = () => {
if (inputValue.trim() !== '') {
setShowAlert(true);
}
};
return(
<button onClick={handleSendClick}>Send</button>
{showAlert && <Alerts />}
);

(inputValue.trim() !== '') checks whether the inputValue variable, which contains the content of an input field, is not an empty string after removing leading and trailing whitespace using the trim() method.

Live code example

Code explanation

  • In src/components/Alerts.jsx:

    • Lines 1–3: Necessary libraries and CSS file is imported.

    • Lines 7–10: A function is created to handle the “OK” button of the alert component. It will reload the React window to restart the application.

    • Line 12: This line creates the alert box and adds the necessary CSS to the alert component.

    • Line 15: This adds an icon to the alert component.

    • Lines 16–17: This creates an “OK” button for the alert component, which is being handled by the function handleOKButton we created at the start of Alerts.jsx file.

  • In src/App.js:

    • Lines 5–6: This initializes state variables using useState hook.

    • Lines 8–12: This defines a function handleSendClick which is triggered when the “Send” button is clicked. It checks if the inputValue is not empty (after removing leading and trailing whitespace) and sets showAlert to true if it’s not empty.

    • Lines 15–20: The return statement renders an input field to allow the user to enter text. On entering text, the inputValue is updated with the entered text.

    • Line 21: This creates the “Send” button that triggers the handleSendClick function.

    • Line 22: This conditionally renders the Alerts component based on the value of showAlert.

Quiz

Let’s have a small quiz to understand the concepts better:

Alert component in React JS

Q

Complete the code below:

const handleSendClick = () => {
    //Write your code here
  };
  return (
    <div className="App">
    <input
        type="text"
        placeholder="Enter text..."
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <button onClick={handleSendClick}>Send</button>
      {showAlert && <Alerts />}
    </div>
  );
A)
if (inputValue) {
      setShowAlert(true);
    }
B)
if (inputValue.trim() !== '') {
      setShowAlert(true);
    }
C)
if (inputValue.trim() !== '') {
    }
D)
setShowAlert(true);

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved