2
\$\begingroup\$

I'm building a modal form in React. It collects a name, image URL, and weather selection. It works, but I’d like to improve:

  • Code structure
  • State handling
  • Reusability
  • Accessibility

Here’s the code:

import React, { useState } from "react";
import "./ModalWithForm.css";

function ModalWithForm({ isOpen, onClose }) {
  const [formData, setFormData] = useState({
    name: "",
    image: "",
    weather: "hot",
  });

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Form submitted:", formData);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal__header">
          <h2 className="modal__title">New garment</h2>
          <button className="modal__close-btn" onClick={onClose}>✕</button>
        </div>

        <form className="modal__form" onSubmit={handleSubmit}>
          <div className="modal__input-group">
            <label htmlFor="name" className="modal__label">Name</label>
            <input
              type="text"
              id="name"
              name="name"
              className="modal__input"
              value={formData.name}
              onChange={handleInputChange}
              required
            />
          </div>

          <div className="modal__input-group">
            <label htmlFor="image" className="modal__label">Image</label>
            <input
              type="url"
              id="image"
              name="image"
              className="modal__input"
              value={formData.image}
              onChange={handleInputChange}
              required
            />
          </div>

          <div className="modal__weather-section">
            <p>Select the weather type:</p>
            {["hot", "warm", "cold"].map((type) => (
              <label key={type}>
                <input
                  type="radio"
                  name="weather"
                  value={type}
                  checked={formData.weather === type}
                  onChange={handleInputChange}
                />
                {type}
              </label>
            ))}
          </div>

          <button type="submit" disabled={!formData.name || !formData.image}>
            Add garment
          </button>
        </form>
      </div>
    </div>
  );
}
\$\endgroup\$

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.