5

im trying to use a ref for focusing on the element when onBlur. I'm using react v.16.9.0 My code is this:

const handleKeyDown = (e, element, index) => {
  element.current.focus();
  event.preventDefault();
};

const pinDigitBuilder = () => {
  const arr = Array(...Array(TOTAL_PIN_DIGITS));
  return arr.map((x, i) => {
    const inputRef = useRef(null);
    console.log(inputRef);
    return (
      <Field
        key={`${PIN_DIGIT}${i + 1}`}
        id={`${PIN_DIGIT}${i + 1}`}
        name={`${PIN_DIGIT}${i + 1}`}
        ref={inputRef}
        component={InputTextField}
        className="text xxs2"
        classNameInvalid="text xxs2 error"
        type="text"
        divClassName="fieldWrap"
        maxLength={1}
        normalize={keepNumbersOnly}
        errorStyle={{ display: 'none' }}
        autoComplete="off"
        onBlur={(e) => { handleKeyDown(e, inputRef, i); }}
      />
    );
  });
};

When i click outside the field an error occured saying that element.current.focus();. I dont get it. I use useRef as explained with details in the docs and i dont know what im missing. Any ideas?

RamAlx
  • 6,976
  • 23
  • 58
  • 106

2 Answers2

4

I'm assuming <Field /> is a Functional component. And inside <Field /> component there is a input element. If that is the case then you have to use forwardref to pass down ref to child. Here is the reference link

https://reactjs.org/docs/forwarding-refs.html.

reachtokish
  • 347
  • 1
  • 10
2

I don't know if you found the answer but I had the same issue with a double problem.

  1. I was using a class stateless component so no ref and this is why I am assuming you were getting the error (How can I attach to a stateless component's ref in React?)
  2. In order to fix this issue you need add a tabIndex in order to set focus in a div (not input element) (Is it possible to focus on a <div> using JavaScript focus() function?)