I'm trying to adapt the code below to use react useRef as opposed to using document.querySelector(selector) as HTMLElement; as it's not the best practice in react. I'm trying to achieve functionality that scrolls to the first error on a Formik form, this code does work but how I can do this with React useRef instead?
here is the code:
import React, { useEffect } from 'react';
import { useFormikContext } from 'formik';
const FocusError = () => {
const { errors, isSubmitting, isValidating } = useFormikContext();
useEffect(() => {
if (isSubmitting && !isValidating) {
let keys = Object.keys(errors);
if (keys.length > 0) {
const selector = `[name=${keys[0]}]`;
const errorElement = document.querySelector(selector) as HTMLElement;
if (errorElement) {
errorElement.focus();
}
}
}
}, [errors, isSubmitting, isValidating]);
return null;
};
export default FocusError;
//Put it within formiks Form.
<Formik ...>
<Form>
...
<FocusError />
</Form>
</Formik>