Skip to content

Instantly share code, notes, and snippets.

@munkhorgil
Last active June 9, 2020 15:17
Show Gist options
  • Save munkhorgil/d4a27bd5fc0ba7b80c065211dea82567 to your computer and use it in GitHub Desktop.
Save munkhorgil/d4a27bd5fc0ba7b80c065211dea82567 to your computer and use it in GitHub Desktop.
React Native handling multiple textInputs
/**
* React Native - Handling multiple TextInputs
* ---------------
* [1] [2] [3] [4]
* ---------------
* Author: Munkh-Orgil
* Date: 01/21/2020
*/
import React from 'react';
import { View, TextInput } from 'react-native';
class App extends React.Component {
constructor(props) {
super(props);
this.inputRefs = [];
this.state = {
values: []
};
for (let i = 0; i < 4; i++) {
this.inputRefs.push(React.createRef());
}
}
handleOnChangeText(value, index) {
const prevValues = [...this.state.values];
prevValues[index] = value;
this.setState({ values: prevValues }, () => {
return index !== 3 && this.inputRefs[index + 1].current.focus();
});
}
handleOnSubmitEditing(index) {
if (index === 3) {
return // do something
}
return this.inputRefs[index].current.focus();
}
render() {
const { values } = this.state;
return (
<View>
{this.inputRefs && this.inputRefs.map((inputRef, index) => {
const onChangeText = value => this.handleOnChangeText(value, index);
const onSubmitEditing = () => this.handleOnSubmitEditing(index);
return (
<TextInput
key={index}
ref={inputRef}
value={values[index]}
maxLength={1}
keyboardType="numeric"
returnKeyType={index === 3 ? 'done' : 'next'}
onChangeText={onChangeText}
onSubmitEditing={onSubmitEditing}
/>
);
})}
</View>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment