Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  13] [ 5]  / answers: 1 / hits: 24613  / 6 Years ago, sat, february 10, 2018, 12:00:00

I'm trying to apply a mask in a TextField component, but im without success.


I already tried this solution but not worked. I tried every way but seems to not work anymore.


I tried to follow the instructions given in docs but they use the Input component and this component is breaking my design.


Anyone knows a way to mask the TextField component? I'm using material-ui 1.0.0-beta.24


More From » reactjs

 Answers
5

Use InputProps to set the mask directly on a TextField component. For example, suppose your desired mask is represented by the TextMaskCustom component. Then, instead of applying it to an Input directly, you can apply it to your TextField using the InputProps like so:



<TextField
id=maskExample
label=Mask Example
className={classes.textField}
margin=normal
InputProps={{
inputComponent: TextMaskCustom,
value: this.state.textmask,
onChange: this.handleChange('textmask'),
}}
/>


This works because a TextField is actually a wrapper around an Input component (with some other things mixed in). The InputProps prop of the TextField gives you access to the internal Input, so you can set the mask that way while preserving the styling of the TextField component.



Here's a full working example adapted from the demos in the docs:



import React from 'react';
import MaskedInput from 'react-text-mask';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import TextField from 'material-ui/TextField';

const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
input: {
margin: theme.spacing.unit,
},
});

const TextMaskCustom = (props) => {
const { inputRef, ...other } = props;

return (
<MaskedInput
{...other}
ref={inputRef}
mask={['(', /[1-9]/, /d/, /d/, ')', ' ', /d/, /d/, /d/, '-', /d/, /d/, /d/, /d/]}
placeholderChar={'u2000'}
showMask
/>
);
}

TextMaskCustom.propTypes = {
inputRef: PropTypes.func.isRequired,
};

class FormattedInputs extends React.Component {
state = {
textmask: '(1  )    -    ',
};

handleChange = name => event => {
this.setState({
[name]: event.target.value,
});
};

render() {
const { classes } = this.props;
return (
<div className={classes.container}>
<TextField
id=maskExample
label=Mask Example
className={classes.textField}
margin=normal
InputProps={{
inputComponent: TextMaskCustom,
value:this.state.textmask,
onChange: this.handleChange('textmask'),
}}
/>
</div>
);
}
}

FormattedInputs.propTypes = {
classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(FormattedInputs);

[#55198] Wednesday, February 7, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;