Home > Back-end >  React - Create multiple useRefs in one line using object or array
React - Create multiple useRefs in one line using object or array

Time:02-21

I want to declare multiple useRefs and have them all in 1 object or an array. If that's not possible, then any means of declaring multiple refs in one line, like array destructuring

I tried these so far, neither worked.

attempt 1

const inputRefs = useRef({ input1: null, input2: null, input3: null, input4: null })

function focusInput() {
    inputRefs.input2.current.focus()
}

return (
    <div>
        <input type="text" ref={inputRefs.input1} />
        <input type="text" ref={inputRefs.input2} />
        <input type="text" ref={inputRefs.input3} />
        <input type="text" ref={inputRefs.input4} />
        <button onClick={focusInput}>focus</button>
    </div>
)

attempt 2

const [input1, input2, input3, input4] = Array(4).fill(useRef(null))

function focusInput() {
    input2.current.focus()
}

return (
    <div>
        <input type="text" ref={input1} />
        <input type="text" ref={input2} />
        <input type="text" ref={input3} />
        <input type="text" ref={input4} />
        <button onClick={focusInput}>focus</button>
    </div>
)

note I only have 4 inputs in the example, but in reality I have much more so hence I want to find a way. Thanks

CodePudding user response:

You can set ref on your inputs wrapper and work with inputs through DOM API.

const containerRef = useRef(null);

function focusInput() {
    const containerNode = containerRef.current;
    containerNode.childNodes[2].focus();
}

return (
    <div ref={containerRef}>
        <input type="text" />
        <input type="text" />
        <input type="text" />
        <input type="text" />
        <button onClick={focusInput}>focus</button>
    </div>
)

CodePudding user response:

Few things to correct.

  1. The useRef is a react hook (which should be defined in the top level of the function). Therefore, to create refs and store them in an array, you should use createRef.
  2. Edit gracious-varahamihira-r620j4

    CodePudding user response:

    kk I found a similar way to my first one but it works. Further suggestions are also welcome

    import { useRef } from "react";
    
    export default function App() {
      const inputRefs = {input1: useRef(null), input2: useRef(null), input3: useRef(null), input4: useRef(null)}
    
      function focusInput() {
        inputRefs.input2.current.focus();
      }
    
      return (
        <div>
          <input type="text" ref={inputRefs.input1} />
          <input type="text" ref={inputRefs.input2} />
          <input type="text" ref={inputRefs.input3} />
          <input type="text" ref={inputRefs.input4} />
          <button onClick={focusInput}>focus</button>
        </div>
      );
    }
    
  • Related