How to declare multiple variable useRef with a loop? Is that possible

Viewed 318

I need to clean up the code to be DRY from my senior.

Initially my logic and code is already working but senior want me to improve my code.

My code is something like this

const firstTextInputRef = useRef(null);
const secondTextInputRef = useRef(null);
const thirdTextInputRef = useRef(null);
const fourthTextInputRef = useRef(null);
const fifthTextInputRef = useRef(null);
const sixthTextInputRef = useRef(null);

const onOtpKeyPress = index => {
    return ({nativeEvent: {key: value}}) => {
        // auto focus to previous InputText if value is blank and existing value is also blank
        if (value === 'Backspace' && otpArray[index] === '') {
            if (index === 1) {
                firstTextInputRef.current.focus();
            } else if (index === 2) {
                secondTextInputRef.current.focus();
            } else if (index === 3) {
                thirdTextInputRef.current.focus();
            } else if (index === 4) {
                fourthTextInputRef.current.focus();
            } else if (index === 5) {
                fifthTextInputRef.current.focus();
            }
        }
    };
};

What I am doing now is I am listening to keypress and change the focus of the keyboard from 1 input to another.

What he want me to do is I need to declare the ref inside a loop and improve the if else statement

This snippet is what he suggest.

let otpTextInputs = [];
for(let i = 0; ;i!=5;i++) {
 // put new ref into the array
}

I already tried multiple way and spend more that 2 hours on it and I still don't know how to do it. Can anyone suggest an answer?

1 Answers

You can just create a useEffect that runs when you first initialize your component that generates the inputs programmatically and sets their ref. That way you can set up a state where you can store all the refs and then access them.

Here is a CodeSandbox demo with the proposed solution.

Related