Untitled

mail@pastecode.io avatar
unknown
javascript
21 days ago
2.0 kB
2
Indexable
Never
import { forwardRef, useRef, useState } from 'react';
import { Container, InputNumber } from './styles';
import {
  NativeSyntheticEvent,
  TextInput,
  TextInputKeyPressEventData,
} from 'react-native';

interface IInputCodeNumberProps {
  length: number;
}

const InputCodeNumber = forwardRef(({ length }: IInputCodeNumberProps, ref) => {
  const [codeNumber, setCodeNumber] = useState<string[]>(
    Array(length).fill(''),
  );
  const codeNumberInputsRef = useRef<TextInput[]>([]);

  const handleInputChange = (inputedValue: string, index: number) => {
    // Verifica se usuário não digitou algum valor além do número
    if (isNaN(Number(inputedValue))) {
      return;
    }

    const actualInputRef = codeNumberInputsRef.current;

    // Pega o array de valores atuais e modifica apenas o índice solicitado
    const newCodeNumber = [...codeNumber];
    newCodeNumber[index] = inputedValue;

    setCodeNumber(newCodeNumber);

    if (inputedValue && index < actualInputRef.length - 1) {
      actualInputRef[index + 1].focus();
    }
  };

  const handleOnKeyPress = (
    event: NativeSyntheticEvent<TextInputKeyPressEventData>,
    index: number,
  ) => {
    const isBackSpace = event.nativeEvent.key === 'Backspace';

    // Verifica se foi digitado backspace, se o input atual está vazio e o índice for maior que 0
    if (isBackSpace && codeNumber[index] === '' && index > 0) {
      codeNumberInputsRef.current[index - 1].focus();
    }
  };

  return (
    <Container>
      {codeNumber.map((digito, index) => {
        return (
          <InputNumber
            key={index}
            keyboardType="numeric"
            onChangeText={text => handleInputChange(text, index)}
            onKeyPress={event => handleOnKeyPress(event, index)}
            maxLength={1}
            value={codeNumber[index]}
            ref={actualRef => (codeNumberInputsRef.current[index] = actualRef!)}
          />
        );
      })}
    </Container>
  );
});

export { InputCodeNumber };
Leave a Comment