Created
August 26, 2017 06:01
-
-
Save evturn/42aee6b65178659ebd00ee92868a3a3e to your computer and use it in GitHub Desktop.
Simple component for managing an arbitrary amount of digits as input for a pin.
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, { Component } from 'react'; | |
import { StyleSheet, TextInput, View } from 'react-native'; | |
/* | |
* | |
* class SomeComponent extends Component { | |
* onValueChange = pin => { | |
* return someOperation(pin); | |
* } | |
* | |
* render() { | |
* return ( | |
* <PinInput | |
* digits={4} | |
* onValueChange={this.onValueChange} /> | |
* ); | |
* } | |
* } | |
* | |
*/ | |
class PinInput extends Component { | |
static defaultProps = { | |
digits: 4, | |
} | |
state = { | |
value: [], | |
} | |
componentWillUpdate(nextProps, nextState) { | |
if (nextState.value !== this.state.value) { | |
this.onValueChange(nextState); | |
} | |
} | |
onChangeText = text => { | |
const str = text + ''; | |
this.setState({value: str.split('')}); | |
} | |
onFocus = e => { | |
this.inputInstance.focus(); | |
} | |
onValueChange = nextState => { | |
const parsedVal = parseInt(nextState.value.join('')); | |
const value = parsedVal >= 0 ? parsedVal : undefined; | |
return this.props.onValueChange(value); | |
} | |
render() { | |
const { value } = this.state; | |
const inputs = Array.from({length: this.props.digits}); | |
return ( | |
<View style={styles.root}> | |
<TextInput | |
autoFocus | |
keyboardType="numeric" | |
maxLength={4} | |
onChangeText={this.onChangeText} | |
ref={i => this.inputInstance = i} | |
style={styles.hidden} /> | |
<View style={styles.inputs}> | |
{inputs.map((_, ii) => | |
<TextInput | |
caretHidden={true} | |
keyboardType="numeric" | |
maxLength={1} | |
onFocus={this.onFocus} | |
style={styles.input} | |
value={value[ii] || ''} />)} | |
</View> | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
hidden: { | |
height: 0, | |
width: 0, | |
position: 'absolute', | |
}, | |
input: { | |
backgroundColor: '#fff', | |
height: 60, | |
width: 50, | |
textAlign: 'center', | |
}, | |
inputs: { | |
flex: 1, | |
flexDirection: 'row', | |
justifyContent: 'center', | |
}, | |
root: { | |
flex: 1, | |
justifyContent: 'center', | |
alignItems: 'center', | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment