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
    />
)}
4
  • 1
    Does this answer your question? Using multiple refs on a single React element Commented Jul 3, 2021 at 16:53
  • 1
    why do you need 2 refs ?? basically the ref is a reference to a dom element Commented Jul 3, 2021 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 Commented Jul 3, 2021 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. Commented Jul 3, 2021 at 17:33

1 Answer 1

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;
      }}
    />
)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.