Introduction
An input mask is a string expression that constrains user input.
In this article, we’ll look at how to use an input mask to enforce input format in a React app.
Getting Started
We can add an input that enforces an input mask in a React app.
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.
For instance, if we want to incorporate an input that takes a North American phone number, then we can write:
import React from "react";
import InputMask from "react-input-mask";
export default function App() {
return (
<div className="App">
<InputMask mask="+1\(999) 999-9999" maskChar=" " />
</div>
);
}
The mask
prop has the input mask.
And the maskChar
has the character we want to cover over the unfilled parts of a mask.
We can also use the formatChars
prop to specify the format characters with the characters as keys and the corresponding regex string as a value.
alwaysShowMask
is a boolean prop to specify whether we want to show the mask when input is empty and has no focys.
inputRef
prop lets us specify the input ref of the input element so that we can manage focus, selection, etc.
We can use the formatChars
prop as follows:
import React from "react";
import InputMask from "react-input-mask";
export default function App() {
return (
<div className="App">
<InputMask
formatChars={{
"9": "[0-9]",
a: "[A-Za-z]",
"*": "[A-Za-z0-9]"
}}
mask="+1\(999) 999-9999"
maskChar=" "
/>
</div>
);
}
Setting State
We can set the input value to a state by using a change handler and the useState
hook as usual with the InputMask
component.
For instance, we can write:
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 added onChange={e => setPhone(e.target.value)}
to call setPhone
when the input value changes.
It also takes a value
prop so that we can set the input value to the phone number that we can change.
Now when we type something into the input, we’ll see the inputted value displayed below it.
Conclusion
We can add input with format being enforced by an input mask by using the react-input-mask
package.
Using the component in the package, we can set the mask to enforce the format and handle input value changes like a regular input element.
The mask format can also be adjusted to our liking.