envoc-form
Version:
Envoc form components
49 lines (48 loc) • 2.17 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var formik_1 = require("formik");
var smoothscroll_polyfill_1 = __importDefault(require("smoothscroll-polyfill"));
/** Function to scroll to the field that has an error. */
function FocusError(props) {
var _a = (0, formik_1.useFormikContext)(), errors = _a.errors, isSubmitting = _a.isSubmitting, isValidating = _a.isValidating;
smoothscroll_polyfill_1.default.polyfill();
(0, react_1.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;
}
exports.default = FocusError;
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);
};