3
\$\begingroup\$

I created an input that accepts and formats phone numbers into XXX-XXX-XXX. The user should be able to type numbers and the dashes should insert themselves automatically.

Example #1: The user types 1 2 3 4. The input shows 123-4.

Example #2: The user types 1 2 3 4 BACKSPACE. The input shows 123. Note the lack of dash!

This is my solution with react.js, typescript and use state. I didn't implement validation, that only numeric can be inserted. How can I improve my solution with react, typescript and use state?

My solution:

import { useState } from "react";

export function PhoneNumberBonus() {
  const [phone, setPhone] = useState("");

  function onChange(value: string) {
    if (isNonEmptyString(value) && value.length % 4 == 0 && value.slice(-1) != "-") {
      let index: number = value.length - 1;
      value = addStr(value, index, "-");
      setPhone(value);
    }
    else {
      setPhone(value);
    }
  }

  function addStr(str: string, index: number, stringToAdd: string) {
    return str.substring(0, index) + stringToAdd + str.substring(index, str.length);
  }

  function isNonEmptyString(str: string) {
    return str && str.length > 0;
  }


  return <div>Bonus: Phone Number
    <input value={phone} onChange={(e) => onChange(e.target.value)} />

  </div>;
}

\$\endgroup\$
4
  • \$\begingroup\$ Why not use one of the many libraries that are available? npmjs.com/search?q=react%20phone%20number \$\endgroup\$
    – BCdotWEB
    Sep 29 '21 at 6:41
  • \$\begingroup\$ yes, but I would like to create myself, because I learn react.js \$\endgroup\$
    – dborovsky
    Sep 29 '21 at 8:48
  • \$\begingroup\$ You haven't implemented the second example, right? \$\endgroup\$
    – sschmeck
    Oct 6 '21 at 11:39
  • \$\begingroup\$ I implemented two examples \$\endgroup\$
    – dborovsky
    Oct 6 '21 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.