Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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