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?
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