GoncharukOrg / react-input

100 stars 7 forks source link

Skip replacing some characters? #5

Closed cjstock closed 1 year ago

cjstock commented 1 year ago

I want to create a component that will display a Social Security Number like this: XXX-XX-___ Where only the "" are replaced with digits while typing, and the "X" are not replaced. How would I go about doing this?

GoncharukBro commented 1 year ago

You can use the following pattern:

import { useMask } from "@react-input/mask";

export default function App() {
   const maskRef = useMask({
     mask: "XXX-XX-____",
     replacement: { _: /\d/ }
   });

   return <input ref={maskRef} />;
}

It is important to note that "X" characters are mask characters and will not be replaced or store a value other than "X", so target.value will always contain a value matching the regular expression /^XXX-XX-\d\d\d\d$/.

If you need to display a value that is different from the input value, you can use the "substitute" input element. This is valid because the state of the input must match the displayed value.

Please provide feedback if possible.