この解答例はChatGPTによって生成されています,正しいかは自己判断で。

BFE.devでのAI解答例 - React コーディング問題
10. phone number input

import React, { useState } from "react";

const PhoneNumberInput = () => {
  const [value, setValue] = useState("");

  const handleInputChange = (e) => {
    let inputValue = e.target.value;
    // only allowing numerical digits
    inputValue = inputValue.replace(/[^\d]/g, "");
    // adding parenthesis after the 4th digit
    if (inputValue.length > 3 && inputValue.length < 7) {
      inputValue = `(${inputValue.slice(0, 3)})${inputValue.slice(3)}`;
    }
    // adding "-" before the 7th digit
    if (inputValue.length > 6) {
      inputValue = `(${inputValue.slice(0, 3)})${inputValue.slice(
        3,
        6
      )}-${inputValue.slice(6)}`;
    }
    setValue(inputValue);
  };

  return (
    <div>
      <input type="text" value={value} onChange={handleInputChange} />
    </div>
  );
};

export default PhoneNumberInput;

Regarding the follow-up question, in this implementation, the caret position will not jump to the end if the user removes some digits in the middle. The caret position will stay where it is, so the user can continue editing comfortably. However, this behavior might not be desirable, as it could cause confusion for the user. It is recommended to test and consider the desired behavior for the caret position.