DEV Community

Cover image for Creating a Simple Modal Component in React with TypeScript for Beginners-
Sanjana Kumari
Sanjana Kumari

Posted on • Edited on

Creating a Simple Modal Component in React with TypeScript for Beginners-

Introduction:

Modal windows are a common UI element used to display important information or requests for user input without navigating away from the current page. In this beginner-friendly tutorial, we'll explore how to create a simple modal component in React using TypeScript within a Next.js project. TypeScript provides static typing and enhanced tooling, making it easier to catch errors and refactor code as your application grows.

Setting Up the Project:

Before we dive into coding, let's make sure you have everything set up. Ensure you have Node.js installed on your machine. Next.js projects are typically created using npm or yarn. You can generate a new Next.js project with TypeScript support by running one of the following commands:

npx create-next-app@latest my-next-app --ts
# or
yarn create next-app my-next-app --typescript

Enter fullscreen mode Exit fullscreen mode

Replace "my-next-app" with the desired name of your project.

Creating the Modal Component:

Our modal component will consist of two parts: the trigger button that opens the modal and the modal itself. Let's start by creating the modal component:

// components/ModalBox.tsx
import React from "react";

interface ModalProps {
  onClose: () => void;
}

export default function ModalBox({ onClose }: Props) {
  return (
    <div className="fixed top-0 left-0 w-full h-full flex items-center justify-center bg-gray-500 bg-opacity-70">
      <div className="bg-white rounded-md overflow-hidden max-w-md w-full mx-4">
        <nav className="bg-black text-white flex justify-between px-4 py-2">
          <span className="text-lg">Modal</span>
          <button
            className="bg-red-300 bg-opacity-50 py-1 px-2 hover:bg-red-500 hover:bg-opacity-70 transition-all rounded-full text-sm"
            onClick={onClose}
          >
            &#10005;
          </button>
        </nav>
        <div className="text-3xl font-bold py-8 pl-4">Hello Modal!</div>
      </div>
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

In this TypeScript version, we define an interface ModalProps to specify the type of props that the modal component will receive. This adds type safety and helps in catching errors during development.

Creating the Parent Component:

Now, let's create the parent component that will use our modal:

// pages/index.tsx
import React, { useState } from "react";
import ModalBox from "../components/ModalBox";

export default function Home() {
  const [isModalVisible, setIsModalVisible] = useState(false);

  const handleShowModal = () => {
    setIsModalVisible(true);
  };

  const handleCloseModal = () => {
    setIsModalVisible(false);
  };

  return (
    <div className="relative">
      <button
        className="bg-green-600 hover:bg-green-500 transition duration-150
      text-white px-5 py-2 rounded-md absolute top-4 left-8 transform"
        onClick={handleShowModal}
      >
        Show Modal
      </button>
      {isModalVisible && <ModalBox onClose={handleCloseModal} />}
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

In this TypeScript version of the parent component, we utilize React's useState hook to manage the visibility of the modal. We also define the types of the component to enhance type safety and catch potential errors during development.

Conclusion:

Well done! You've built a basic modal component in React using TypeScript within a Next.js project. TypeScript's static typing and improved tooling offer a more reliable and efficient development process, particularly as project expands. Keep exploring and experimenting with various features to enhance Next.js and React skills further. Happy coding!✨

Top comments (0)