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>
 );
}
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Aug 5 at 11:15
\$\endgroup\$

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.