@braineet/ui
Version:
Braineet design system
37 lines • 1.33 kB
JavaScript
import { useEffect } from 'react';
import { getIn, useFormikContext } from 'formik';
export var FocusError = function FocusError(_ref) {
var _ref$focusDelay = _ref.focusDelay,
focusDelay = _ref$focusDelay === void 0 ? 100 : _ref$focusDelay,
onFocus = _ref.onFocus;
var _useFormikContext = useFormikContext(),
isSubmitting = _useFormikContext.isSubmitting,
touched = _useFormikContext.touched,
isValidating = _useFormikContext.isValidating,
errors = _useFormikContext.errors;
useEffect(function () {
if (isSubmitting && !isValidating) {
var errorNames = Object.keys(touched).reduce(function (prev, key) {
if (getIn(errors, key)) {
prev.push(key);
}
return prev;
}, []);
if (errorNames.length && typeof document !== 'undefined') {
var errorElement;
errorNames.forEach(function (errorKey) {
var selector = "[name=\"" + errorKey + "\"]";
if (!errorElement) {
errorElement = document.querySelector(selector);
}
});
setTimeout(function () {
if (errorElement) errorElement.focus();
if (onFocus) onFocus();
}, focusDelay);
}
}
}, [isSubmitting, isValidating, errors, touched, focusDelay]);
return null;
};
export default FocusError;