Skip to content

Instantly share code, notes, and snippets.

@pixelcure
Created July 27, 2018 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixelcure/e477f40b79b255636d0e030b879f5ec7 to your computer and use it in GitHub Desktop.
Save pixelcure/e477f40b79b255636d0e030b879f5ec7 to your computer and use it in GitHub Desktop.
import React from 'react';
import { render } from 'react-dom';
class TelephoneField extends React.Component {
constructor(props) {
super(props);
this.state = { val: '' };
}
handleChange(e) {
const val = e.currentTarget.value;
const replace = ('' + val).replace(/\D/g, '');
const match = replace.match(/^(\d{3})(\d{3})(\d{4})$/);
if (!match) {
this.setState({ val: e.currentTarget.value });
} else {
const val = `(${match[1]}) ${match[2]}-${match[3]}`;
this.setState({ val });
}
}
render() {
return (
<input
type='text'
placeholder='Enter your phone number'
onChange={e => this.handleChange(e)}
value={this.state.val}
/>
);
}
}
render(<TelephoneField />, document.getElementById('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment