DEV Community

itric
itric

Posted on

🤔 How e.target and e.currentTarget is used for Modal in React app ?

In a React application, e.target and e.currentTarget can be used to add closing functionality to a modal when clicked outside of the modal.

Here's how:

Example Code:

import { useState } from 'react'

function App() {
    const [isModalOpen, setIsModalOpen] = useState(false);
    return (
      <div className=" bg-white h-screen w-screen flex flex-col items-center justify-center">
        <button
          onClick={() => {
            setIsModalOpen(true);
          }}
          className="w-full max-w-xs font-bold hover:opacity-70 relative text-white bg-[#635fc7] py-2 rounded-full"
        >
          Open Modal
        </button>

        {isModalOpen &&
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-md"
          onClick={(e) => {
            if (e.target !== e.currentTarget) {
              return; // Click inside the modal; don't close it
            }
            setIsModalOpen(false); // Click outside the modal; close it
          }}
          >
          <div className="max-w-sm relative bg-white rounded-lg p-6">
            <h3>Modal</h3>
            <button
              className="absolute top-2 right-2 text-gray-600 hover:text-gray-900"
              onClick={(e)=> setIsModalOpen(false)}
            >
              &times;
            </button>
            <h2 className="text-2xl mb-4">Modal Content</h2>
        <p>This is a sample modal. Click the &times; to close it. Or Click anywhere outside of the modal </p>
          </div>
        </div>
          }
      </div>
    );
  }
export default App

Enter fullscreen mode Exit fullscreen mode

Explanation :

State Management:

  • A state variable, isModalOpen, is used to manage the visibility of the modal. It's initially set to false.

  • A function, setIsModalOpen, updates the value of isModalOpen.

const [isModalOpen, setIsModalOpen] = useState(false);
Enter fullscreen mode Exit fullscreen mode

Conditional Rendering:

The modal is conditionally rendered based on the value of isModalOpen. If true, the modal is displayed.

{isModalOpen && <Modal />}
Enter fullscreen mode Exit fullscreen mode

Opening and Closing the Modal:

The "Open Modal" button triggers setIsModalOpen(true), which sets isModalOpen to true, rendering the modal.

The modal can be closed by clicking the "×" ("Close Modal") button inside it, which triggers setIsModalOpen(false).

<button onClick={() => setIsModalOpen(true)}>Open Modal</button>
{isModalOpen && <button onClick={() => setIsModalOpen(false)}>Close Modal</button>}

Enter fullscreen mode Exit fullscreen mode

Modal Closing Logic:

The onClick event is attached to the outermost div that acts as the modal's background or overlay.

Inside the event handler:

  1. e.target refers to the actual element that was clicked.

  2. e.currentTarget refers to the element that the event listener is attached to (in this case, the outer div).

To close the modal when a click occurs outside of it, the following logic is implemented:

Event Propagation Check:

Inside the onClickhandler of the outer div, a check is performed: if (e.target !== e.currentTarget). This condition verifies whether the click happened on the outer div itself (e.currentTarget) or on any of its child elements (like the modal content).

Conditional Execution:

If e.targetis not equal to e.currentTarget, it means the click occurred inside the modal (on one of its child elements). In this case, the function returns early, preventing the modal from closing.

If the click was on the outer div (i.e., e.target === e.currentTarget), the modal is closed by setting isModalOpento false.
This approach ensures that the modal only closes when the user clicks outside of it, while clicks inside the modal (on its content or buttons) do not trigger the close action.

   <div 
          onClick={(e) => {
            if (e.target !== e.currentTarget) {
              return; // Click inside the modal; don't close it
            }
            setIsModalOpen(false); // Click outside the modal; close it
          }}
        >
Enter fullscreen mode Exit fullscreen mode

Key Points:

  1. State Management: The visibility of the modal is controlled by a boolean state (isModalOpen), which is toggled based on user interaction.

  2. Event Handling: The combination of e.target and e.currentTargetallows us to differentiate between clicks inside and outside the modal, ensuring that the modal only closes when a click occurs outside its content.

Top comments (0)