CodeBlanks Logo Icon CodeBlanks

Stats widget

Write a stats widget that does an expensive computation with useMemo.

Modal pattern

In this lesson we open a modal to add a new stat. The modal opens and closes via the isOpen state; it renders as a <dialog> or a custom container.

When the form is submitted, onAdd(value) fires and the modal closes. This is the standard pattern for add forms.

This lesson's starting code includes the previous StatCard and StatsPage solution.

Form submission

Inside the modal sits a <form onSubmit={handleSubmit}>. handleSubmit calls e.preventDefault(), reads the input value, fires onAdd(value) and closes the modal.

In React, form submission reloads the page by default; you stop this with preventDefault. For a controlled input you use useState.

This pattern is the foundation of add forms and is common in projects.

Practice AddStatModal component

Write AddStatModal: destructure { isOpen, onAdd, onClose }. If !isOpen, return null. Render a <div> with a <form onSubmit={handleSubmit}>. handleSubmit should call e.preventDefault(), read inputRef.current.value, call onAdd(value) and onClose(). export default AddStatModal.

Starter code

App.jsx
import { useRef } from "react";

// AddStatModal bileşenini buraya yaz

Sample solution

App.jsx
import { useRef } from "react";

function AddStatModal({ isOpen, onAdd, onClose }) {
  const inputRef = useRef(null);
  if (!isOpen) return null;
  function handleSubmit(e) {
    e.preventDefault();
    const value = inputRef.current.value;
    onAdd(value);
    onClose();
  }
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input ref={inputRef} />
        <button type="submit">Add</button>
      </form>
    </div>
  );
}

export default AddStatModal;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How do you close the modal?

  • Reset BrowserRouter
  • Delete the route
  • Clean up useEffect
  • Set isOpen state to false Correct answer

Explanation: Setting isOpen to false closes the modal.

2 Prevent form submit

Question
function handleSubmit(e) {
  e.____();
  onAdd(value);
  setIsOpen(false);
}
Answer
function handleSubmit(e) {
  e.preventDefault();
  onAdd(value);
  setIsOpen(false);
}

Explanation: e.preventDefault() stops the page reload.

3 Stats widget: match the terms

Term Meaning
isOpen Modal state
onAdd Add callback
preventDefault Stop reload
useState Input value

All lessons in Intermediate