0

I'm planning to set to autofocus the last element of the array by using a ref, but I don't know how to do it since I'm already using ref for react-hook-form

I've been to this link, but I don't know how to apply it in my case. How can I use multiple refs for an array of elements with hooks?,

Somebody knows how to inject this two refs to one input?


Here's my ref to auto focus an input

const [inputRef, setInputRef] = useFocus();

And here's my current codes with react-form-hook's ref:

{[...Array(10)].map((x, i) => (
    <input
      type="text"
      name="book"
      className="border mr-px-5"
      ref={register(rules.book)}
      ref={lastElement ? inputRef : null} // conditional focus ref
    />
)}
tempra
  • 2,455
  • 1
  • 12
  • 27
  • 1
    Does this answer your question? [Using multiple refs on a single React element](https://stackoverflow.com/questions/60270678/using-multiple-refs-on-a-single-react-element) – Domi Jul 03 '21 at 16:53
  • 1
    why do you need 2 refs ?? basically the ref is a reference to a dom element – S B RAKESH RATH Jul 03 '21 at 17:05
  • so you want to focus an input on the happening of specific event then create a array of every element then focus them as you need ... there is no need of 2 refs also You have `tabIndex` property – S B RAKESH RATH Jul 03 '21 at 17:31
  • @Domi @JagadishLenka I updated the description. I forgot this is a multiple elements. and the `focus` ref should be conditional. The link you sent earlier can't help I think sir. – tempra Jul 03 '21 at 17:33

1 Answers1

0

From frequent try and error, I finally found the solution. The refs can actually use as function and then set two refs in it.

And for the react hook form just pass the event on it to make it work also.

Here's the actual solution:

const [inputRef, setInputRef] = useFocus();

{[...Array(10)].map((x, i) => (
    <input
      type="text"
      name="book"
      className="border mr-px-5"
      ref={(event) => {
        register(event, rules.book);
        if (lastElement) inputRef.current = event;
      }}
    />
)}
tempra
  • 2,455
  • 1
  • 12
  • 27