Created
May 22, 2019 17:50
-
-
Save raullucero/1798a41e178c8ad30244e87c01e3cb78 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 logo from './logo.svg'; | |
import './App.css'; | |
class App extends React.Component { | |
state = { | |
input: '' | |
} | |
handleChangeInput = (e) => { | |
if (!e.target.value) return; | |
const value = e.target.value; | |
const cleanedInput = value.replace(/\D/g, '').substring(0, 10); | |
const formattedNumber = formatNumber(cleanedInput); | |
this.setState({ | |
input: formattedNumber | |
}) | |
} | |
render() { | |
return ( | |
<div> | |
<label for="phone-number">Phone number: </label> | |
<input id="phone-number" type="text" value={this.state.input} onChange={this.handleChangeInput} /> | |
</div> | |
) | |
} | |
} | |
function formatNumber(input) { | |
if (!input.length) return ''; | |
if (input.length < 4) { | |
return `(${input}` | |
} | |
const firstPart = input.substring(0, 3); | |
let secondPart = input.substring(3); | |
if (input.length < 7) { | |
return `(${firstPart}) ${secondPart}`; | |
} | |
const thirdPart = secondPart.substring(3); | |
secondPart = secondPart.substring(0, 3); | |
return `(${firstPart}) ${secondPart}-${thirdPart}`; | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment