How to mask a React Material-UI TextField?

Sometimes, we want to mask a React Material-UI TextField.

In this article, we’ll look at how to mask a React Material-UI TextField.

How to mask a React Material-UI TextField?

To mask a React Material-UI TextField, we can use the react-input-mask package.

We install it by running npm i react-input-mask.

Then, we write:

import * as React from "react";
import TextField from "@material-ui/core/TextField";
import InputMask from "react-input-mask";

export default function App() {
  const [phone, setPhone] = React.useState();
  console.log(phone);

  return (
    <div>
      <InputMask
        mask="(0)999 999 99 99"
        value={phone}
        disabled={false}
        maskChar=" "
        onChange={(e) => setPhone(e.target.value)}
      >
        {() => <TextField />}
      </InputMask>
    </div>
  );
}

to add the InputMask component to add the input mask.

We render the Material UI TextField by using () => <TextField /> as the render prop of InputMask.

Next, we set the mask prop to the mask we want.

And we set onChange and value to set and get the input value respectively.

Conclusion

To mask a React Material-UI TextField, we can use the react-input-mask package.

We install it by running npm i react-input-mask.