Created
July 27, 2018 20:43
-
-
Save pixelcure/e477f40b79b255636d0e030b879f5ec7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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