Eduardo Lima
Eduardo Lima

Reputation: 143

Mask Textfield component in Material-UI

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

Upvotes: 11

Views: 27871

Answers (1)

Jules Dupont
Jules Dupont

Reputation: 7567

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);

Upvotes: 16

Related Questions