0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ネストされたオブジェクトのキーをinputタグのname属性に入れる方法

Posted at

ネストされたオブジェクトのキーをinputタグのname属性に入れる場合、キーをドット(.)で連結する方法が一般的です。以下に例を示します。

App.js
    const [form, setForm] = useState({
      personalInfo: {
        firstName: "",
        lastName: "",
      },
      contactInfo: {
        email: "",
      },
    });
    
    const handleFormChange = (e) => {
      const { name, value } = e.target;
      const [parentKey, childKey] = name.split("."); // ドットでキーを分割
      setForm((prev) => ({
        ...prev,
        [parentKey]: {
          ...prev[parentKey],
          [childKey]: value,
        },
      }));
    };
    
    return (
      <form>
        <input
          type="text"
          name="personalInfo.firstName"
          value={form.personalInfo.firstName}
          onChange={handleFormChange}
        />
        <input
          type="text"
          name="personalInfo.lastName"
          value={form.personalInfo.lastName}
          onChange={handleFormChange}
        />
        <input
          type="text"
          name="contactInfo.email"
          value={form.contactInfo.email}
          onChange={handleFormChange}
        />
      </form>
    );

上記の例では、ネストされたオブジェクトのキーをドットで連結してname属性に設定しています。handleFormChange関数では、name属性からドットで分割して親キーと子キーを取得し、正しい場所に値を更新しています。

このようにすることで、ネストされたオブジェクトの値を正しく更新することができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?