Skip to main content
Code Review

Return to Question

edited tags
Link
edited title
Link
toolic
  • 14.9k
  • 5
  • 29
  • 205

Is this React modal form implementation following best practices?for name, image and weather

Source Link

Is this React modal form implementation following best practices?

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>
 );
}
default

AltStyle によって変換されたページ (->オリジナル) /