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 5 years have passed since last update.

[React]inputのonChangeを共通化する

Posted at

Form を作るとき、input ごとに handleChangeXxx みたいなのを書いていて、共通化できないかなと思ってゴニョったので :pencil:

name 属性を使う

name 属性を state と揃えれて handleChange 内で key に指定すればいい。

import React, { FC, useState, ChangeEvent } from 'react';

type InputStateType = {
  userName: string;
  note: string;
};

const SharedHandleChange: FC = () => {
  const initialInputState: InputStateType = { userName: '', note: '' };
  const [eachInput, setEachInput] = useState(initialInputState);
  const { userName, note } = eachInput;

  const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target) {
      // e.target.name で key を指定すればいい
      setEachInput({ ...eachInput, [e.target.name]: e.target.value });
    }
  };

  return (
    <>
      <form className={classes.root} noValidate autoComplete="off">
        <input name="userName" type="text" onChange={handleInputChange} />
        <input name="note" type="text" onChange={handleInputChange} />
      </form>
      <div>userName: {userName}</div>
      <div>note: {note}</div>
    </>
  );
};

export default SharedHandleChange;

これで onChange を共通化できた。

今まで一つずる書いていたので楽になったし、こういう書き方ができるのかと勉強になった。

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?