envoc-form
Version:
Envoc form components
43 lines (42 loc) • 1.87 kB
JavaScript
import { useEffect } from 'react';
import { useFormikContext } from 'formik';
import smoothscroll from 'smoothscroll-polyfill';
/** Function to scroll to the field that has an error. */
export default function FocusError(props) {
var _a = useFormikContext(), errors = _a.errors, isSubmitting = _a.isSubmitting, isValidating = _a.isValidating;
smoothscroll.polyfill();
useEffect(function () {
if (!isSubmitting || isValidating) {
return;
}
//This block handles any front-end input validation errors
//e.g. required fields, max characters, etc
var keys = Object.keys(errors);
if (keys.length > 0) {
return scrollToErrorElement(keys);
}
//This block handles any input-specific server-side errors
//e.g. improper email formatting, invalid phone number, etc.
if (props.serverErrors.errors &&
Object.values(props.serverErrors.errors).some(function (x) { return !!x; })) {
var names = Object.keys(props.serverErrors.errors);
return scrollToErrorElement(names);
}
}, [errors, isSubmitting, isValidating, props]);
return null;
}
var scrollToErrorElement = function (keys) {
var firstErrorElement = document.getElementById("".concat(keys[0].toLowerCase(), "-error-scroll-target"));
if (!firstErrorElement || !firstErrorElement.parentNode) {
return;
}
firstErrorElement = firstErrorElement.parentNode;
var headerOffset = -110;
var y = firstErrorElement.getBoundingClientRect().top +
window.pageYOffset +
headerOffset;
window.scrollTo({ top: y, behavior: 'smooth' });
setTimeout(function () {
firstErrorElement === null || firstErrorElement === void 0 ? void 0 : firstErrorElement.focus();
}, 500);
};