CodingNic

Task Actions

Open and Close the Task Modal

Task Actions 12 min read

Open and Close the Task Modal

Open and Close the Task Modal

The starter renders the modal as a visual preview. Now the modal should appear only when the user asks to add a task.

1. Add visibility state in App

Because the header button and modal are both controlled by the application, keep the visibility state in App:

jsx
const [isModalOpen, setIsModalOpen] = useState(false);

2. Open it from the header

Connect the existing Add Task button:

jsx
<button
  className="primary-btn"
  type="button"
  onClick={() => setIsModalOpen(true)}
>
  + Add Task
</button>

3. Render the modal conditionally

Instead of always rendering it, use the state:

jsx
{isModalOpen && (
  <TaskModal />
)}

4. Let the modal request a close

Pass an onClose callback:

jsx
<TaskModal onClose={() => setIsModalOpen(false)} />

Then use that callback for the close and cancel buttons.

The modal does not need to reach into App or modify isModalOpen directly. It simply calls the function it received.

Checkpoint

The Add Task button should open the modal. Close and Cancel should hide it again.

At this point, you have practiced an important React pattern: state lives in the component that owns the decision, while children receive callbacks for actions.