Creating a Custom Alert in React with TypeScript

Alerts are an essential part of user interfaces as they draw attention to critical information or actions. While many libraries like Material-UI provide ready-to-use alert components, building a custom alert from scratch can give you more control over its appearance and behavior. In this blog, we'll walk through the process of creating a custom alert in React with TypeScript, without relying on any external libraries.

Prerequisites:

Before we start, ensure that you have a basic understanding of React and TypeScript, along with a development environment set up with Node.js and npm.

Step 1: Setting up the Project

To begin, create a new React project using the create-react-app tool or your preferred setup. Make sure to enable TypeScript support during project creation.

Step 2: Create the CustomAlert Component

In your project's source folder, create a new TypeScript file named CustomAlert.tsx. This file will contain the code for our custom alert component.

Step 3: Implement the CustomAlert Component

In CustomAlert.tsx, start by importing the necessary modules and defining the component's props:

import React, { useState } from 'react';
 
type CustomAlertProps = {
  open: boolean;
  title: string;
  message: string;
  onClose: () => void;
};
 
const CustomAlert: React.FC<CustomAlertProps> = ({ open, title, message, onClose }) => {
  // Component logic will go here
};

We've defined the CustomAlertProps interface, specifying the expected prop types for the custom alert. The open prop will control the visibility of the alert, title will hold the alert title, message will contain the alert message, and onClose is a callback function to close the alert.

Next, we'll implement the rendering logic for the CustomAlert component:

const CustomAlert: React.FC<CustomAlertProps> = ({ open, title, message, onClose }) => {
  if (!open) {
    return null; // Render nothing if the alert is closed
  }
 
  return (
    <div className="custom-alert-overlay">
      <div className="custom-alert">
        <h2>{title}</h2>
        <p>{message}</p>
        <button onClick={onClose}>Close</button>
      </div>
    </div>
  );
};

In this part, we check if the open prop is false, indicating that the alert should not be displayed. If open is false, we return null to render nothing. Otherwise, we render the alert with its title, message, and a close button.

Step 4: Using the CustomAlert Component

Now that we've created the CustomAlert component, let's use it in our main application component (App.tsx):

import React, { useState } from 'react';
import CustomAlert from './CustomAlert';
 
const App: React.FC = () => {
  const [alertOpen, setAlertOpen] = useState(false);
 
  const handleAlertClose = () => {
    setAlertOpen(false);
  };
 
  const handleShowAlert = () => {
    setAlertOpen(true);
  };
 
  return (
    <div>
      <button onClick={handleShowAlert}>Show Alert</button>
 
      <CustomAlert
        open={alertOpen}
        title="Custom Alert"
        message="This is a custom alert created using React and TypeScript."
        onClose={handleAlertClose}
      />
    </div>
  );
};

In the App component, we maintain a state variable alertOpen to control the visibility of the alert. The handleAlertClose function sets alertOpen to false, closing the alert when the close button is clicked. On the other hand, handleShowAlert sets alertOpen to true, displaying the alert when the "Show Alert" button is clicked.

Conclusion

Congratulations! You've successfully created a custom alert component in React with TypeScript from scratch. By following this guide, you've gained valuable insights into managing state, using TypeScript for prop validation, and creating custom components in React.

Remember that this is a basic implementation, and you can further enhance your custom alert by adding custom styles, animations, or additional functionality based on your specific project requirements. Happy coding!