Skip to content

Instantly share code, notes, and snippets.

@refo
Last active February 17, 2017 12:09
Show Gist options
  • Save refo/480ea5722772da52803e1208f02c19e2 to your computer and use it in GitHub Desktop.
Save refo/480ea5722772da52803e1208f02c19e2 to your computer and use it in GitHub Desktop.
React material-ui HOCs

Dependencies

yarn add material-ui
yarn add vanilla-text-mask
yarn add text-mask-addons
import React from 'react';
const TextField = require('material-ui').TextField;
const vanillaTextMask = require('vanilla-text-mask');
import emailMask from 'text-mask-addons/dist/emailMask';
export default class EmailField extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.maskController = vanillaTextMask.maskInput({
inputElement : this.refs.component.input,
mask : emailMask,
});
}
componentWillUnmount() {
this.maskController.destroy();
}
handleChange(e, newValue) {
// Pass through modified event
this.onChange(e, newValue);
}
render() {
const {onChange, ...otherProps} = this.props;
this.onChange = onChange;
return <TextField ref="component" onChange={this.handleChange} {...otherProps} />
}
}
EmailField.propTypes = TextField.propTypes;
import React from 'react';
const TextField = require('material-ui').TextField;
const vanillaTextMask = require('vanilla-text-mask');
export default class PhoneField extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.mask = ['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.maskController = vanillaTextMask.maskInput({
inputElement : this.refs.component.input,
mask : this.mask,
});
}
componentWillUnmount() {
this.maskController.destroy();
}
parseMaskedValue(value) {
return value.replace(/(^\D*9?\D*0|\D+)/ig, '');
}
handleChange(e, newValue) {
let value = this.parseMaskedValue(newValue);
// Pass through modified event
this.onChange(e, value);
}
render() {
const {onChange, ...otherProps} = this.props;
this.onChange = onChange;
return <TextField ref="component" onChange={this.handleChange} {...otherProps} />
}
}
PhoneField.propTypes = TextField.propTypes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment