-
Install react-input-mask
First, you need to install the react-input-mask package. You can do this using npm or yarn:
npm install react-input-mask
or
yarn add react-input-mask
-
Import InputMask in your component
At the top of your file where you are using the <TextField>, import InputMask:
import InputMask from 'react-input-mask';
import TextField from '@mui/material/TextField'; // Make sure you have this import
-
Wrap your <TextField> with InputMask
Use the InputMask component to wrap your <TextField> and provide the mask pattern. For a CEP, which is formatted as 99999-999, you can set the mask accordingly.
Here's how you can modify your code:
<InputMask
mask="99999-999"
value={cep}
onChange={(e) => setCep(e.target.value)}
>
{() => (
<TextField
label="CEP"
type="text"
sx={{ width: 1 / 3, gridRow: '1' }}
variant="outlined"
/>
)}
</InputMask>
Explanation:
mask="99999-999": Defines the input mask pattern for the CEP.
value={cep} and onChange={(e) => setCep(e.target.value)}: Manages the state of the input field.
- The
InputMask component passes its props to the child function, which returns the <TextField> component.
-
Handle the State Correctly
Ensure that the cep state is initialized in your component and that setCep updates the state properly:
const [cep, setCep] = useState('');
-
Full Example
Putting it all together, your component might look like this:
import React, { useState } from 'react';
import InputMask from 'react-input-mask';
import TextField from '@mui/material/TextField';
function CepInput() {
const [cep, setCep] = useState('');
return (
<InputMask
mask="99999-999"
value={cep}
onChange={(e) => setCep(e.target.value)}
>
{() => (
<TextField
label="CEP"
type="text"
sx={{ width: 1 / 3, gridRow: '1' }}
variant="outlined"
/>
)}
</InputMask>
);
}
export default CepInput;