1

I'm implementing a custom SMS code validation that will display an undefined number of input:

enter image description here

And I would like to manage the focus of these input, but I don't know how.

Actually, I've my custom text input like that :

export function ConfirmationCodeInput(props) {
return (
    <TextInput
        style={styles.confirmationCodeInput}
        keyboardType={"number-pad"}
        maxLength={1}
        ref={props.innerRef}
        secureTextEntry={true}
        selectionColor={'transparent'}
        returnKeyType={"next"}
        onChangeText={(event) => props.onTextChange(event)}
    />
)

And my parent component:

export function ConfirmationCode(props) {
let refs = [];
const [codeValue, setCodeValue] = useState(null);

function focusNextField(key) {
    //What to do here ?
}

function createInputs(): Array<any> {
    let inputs = [];
    for (let i = 0; i < props.codeLength; i++) {
        const ref = React.createRef();
        refs[i] = ref;
        const input = <ConfirmationCodeInput key={i}
                                             innerRef = {ref}
                                             onTextChange ={focusNextField}
        />;
        inputs.push(input);
    }

    return inputs;
}

return (
    <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
        {createInputs()}
    </View>
)

How to manage that?

norbitrial
  • 14,716
  • 7
  • 32
  • 59
Toto NaBendo
  • 290
  • 3
  • 26

1 Answers1

0

A better way to do this would be to define a hidden input that you focus and then use the value of that input to display in your other inputs.

export function ConfirmationCode(props) {
  const [codeValue, setCodeValue] = useState(null);


  function createInputs(): Array<any> {
      let inputs = [];
      for (let i = 0; i < props.codeLength; i++) {
          const input = <ConfirmationCodeInput key={i}
                                               value={codeValue[i] ? codeValue[i] : ''}
          />;
          inputs.push(input);
      }

      return inputs;
  }

  return (
      <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
        <TextInput
            keyboardType="numeric"
            style={{ width: 1, height: 1, opacity: 0 }}
            maxLength={6}
            caretHidden={true}
            autoFocus
            onChangeText={text => setCodeValue(text)}
         />
        {createInputs()}
      </View>
  )

Something like this.

Dagur Leó
  • 698
  • 4
  • 13