Skip to content

Instantly share code, notes, and snippets.

@nirtamir2
Last active July 17, 2018 16:39
Show Gist options
  • Save nirtamir2/30eef799175c4a14d7deab1e207b0be7 to your computer and use it in GitHub Desktop.
Save nirtamir2/30eef799175c4a14d7deab1e207b0be7 to your computer and use it in GitHub Desktop.
Phone input field
import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
import PhoneInputField from './components/PhoneInputField'
class App extends Component {
state = {
phone: ''
}
onChange = value => {
this.setState({ phone: value })
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<PhoneInputField
value={this.state.phone}
onChange={this.onChange}
stateCode="+1"
placeholder="Start typing a phone number"
/>
</div>
)
}
}
export default App
import React, { Component } from 'react'
class PhoneInputField extends Component {
input = React.createRef()
getNumbers = text => text.replace(/[^\d]/gi, '')
setSpaces = number => {
return new Array(number).fill(' ').join('')
}
formatText = event => {
const text = event.target.value
const numbers = this.getNumbers(text)
if (numbers.length === 0) {
this.props.onChange('')
} else if (numbers.length >= 10) {
this.props.onChange(numbers)
} else {
this.props.onChange(this.formatPhone(numbers))
}
}
formatPhone = numbers => {
const spacedStart = this.wrapWithSpaces(numbers.substring(0, 3), 3)
const separator = numbers.length > 6 ? '-' : ''
return (
`(${spacedStart}) ` +
numbers.substring(3, 6) +
separator +
numbers.substring(6)
)
}
wrapWithSpaces = (text, length) => {
if (length > text.length) {
return text + this.setSpaces(length - text.length)
}
return text
}
componentDidUpdate() {
const numbersLength = this.getNumbers(this.props.value).length
if (numbersLength <= 3) {
this.input.current.setSelectionRange(numbersLength + 1, numbersLength + 1)
}
}
formatValue = text => {
if (!text.length) {
return ''
}
return this.props.stateCode + this.getNumbers(text)
}
render() {
return (
<div>
<input
type="text"
onInput={this.formatText}
placeholder={this.props.placeholder}
value={this.props.value}
ref={this.input}
/>
<p>Value: {this.formatValue(this.props.value)}</p>
</div>
)
}
}
export default PhoneInputField
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment