We can use the react-input-mask
library to enforce the format of an input box to be a phone number.
The react-input-mask
package makes this very easy.
First, we run:
npm install react-input-mask --save
to install the package in our React project.
Then we can use it by adding it component provided by the package and specify the format of the input that we want to accept.
We can then use it as follows in a React component:
import React from "react";
import InputMask from "react-input-mask";
export default function App() {
const [phone, setPhone] = React.useState("");
return (
<div className="App">
<InputMask
value={phone}
onChange={e => setPhone(e.target.value)}
mask="+1\(999) 999-9999"
maskChar=" "
/>
<p>{phone}</p>
</div>
);
}
We import the InuptMask
component. In it, we pass in the mask
prop, which contains the phone number mask.
We want to enforce the North American phone number format, so we write +1\(999) 999-9999
as the value of the mask so that we’ve to type in a North American phone number.
The value
prop is the same as the value
prop of a regular input element, it takes the state with the value that’s inputted.
The onChange
prop is also the same as the onChange
handler for an input element.
It sets the value in the input box to a state in our example by getting e.target.value
and calling setPhone
in it.
maskChar
has the character to display when the position doesn’t have anything entered yet.
We also have the phone
value displayed below the input.
Now the input box enforces the North American phone number format.
Also, we’ll see the entered value displayed after we enter something.
With the react-input-mask
package, we can add a React component to enforce a phone number mask easily.