0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactでクレジットカード登録のUIを作ってみた

Posted at
import "./App.css";
import { useForm } from "react-hook-form";

interface CardNumberType {
  [key: string]: string;
  cardNumber0: string;
  cardNumber1: string;
  cardNumber2: string;
  cardNumber3: string;
}

function App() {
  const { register, handleSubmit, setFocus } = useForm<CardNumberType>();

  const onSubmit = (data: CardNumberType) => {
    console.log(data);
  };

  const handleKeyUp = (
    index: number,
    event: React.KeyboardEvent<HTMLInputElement>
  ) => {
    if (
      event.target instanceof HTMLInputElement &&
      event.target.value.length === event.target.maxLength
    ) {
      const nextIndex = index + 1;
      if (nextIndex < 4) {
        setFocus(`cardNumber${nextIndex}`);
      }
    }
  };
  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="input-group">
          {Array(4)
            .fill(null)
            .map((_, index) => (
              <div key={index} className="input-group">
                <input
                  {...register(`cardNumber${index}`)}
                  type="text"
                  key={index}
                  maxLength={4}
                  onKeyUp={(event) => handleKeyUp(index, event)}
                />
                {index < 3 && <span>-</span>}
              </div>
            ))}
        </div>
        <button type="submit">送信</button>
      </form>
    </div>
  );
}

export default App;

4文字入力が終わったら次にフォーカスが当たるようにしてます。
useFormが結構便利です!
cssはお好きなようにしてくださいw

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?