diff --git a/src/pages/GiftAid/GiftAid.js b/src/pages/GiftAid/GiftAid.js index c75e056c..45531891 100644 --- a/src/pages/GiftAid/GiftAid.js +++ b/src/pages/GiftAid/GiftAid.js @@ -7,7 +7,6 @@ import axios from 'axios'; import UpdateForm from './UpdateForm'; import SubmitForm from './SubmitForm'; - // context import AppContext from '../../context/AppContext'; @@ -28,9 +27,6 @@ import { getRoute, } from './utils/Utils'; - -let scrollTimeout; - function GiftAid(props) { // initialise and get props from context @@ -99,7 +95,7 @@ function GiftAid(props) { * Handle validity state on component update */ useEffect(() => { - // if validation fails, scroll to error + // Update validation accordingly on update if ((formValidityState.showErrorMessages && !formValidityState.formValidity && formValidityState.validating) || formValidityState.urlTransactionId.valid === false ) { // update validation state @@ -110,27 +106,12 @@ function GiftAid(props) { } }, []); - /** - * Handle scroll to error on component update - */ - useEffect(() => { - scrollTimeout = setTimeout(() => { - scrollToError(formValidityState); - }, 500); - return () => { - // clear timeout on component unmount - clearTimeout(scrollTimeout); - } - }); - - /** * Updates validation state for form fields * @param childState * @param name */ const setFieldValidity = (childState, name) => { - const prevStateField = fieldValidation[name]; const fieldUndefined = prevStateField === undefined; const valueUndefined = typeof prevStateField !== 'undefined' && prevStateField.value === undefined; @@ -202,6 +183,10 @@ function GiftAid(props) { pathname: pathParams.sorryPath, // redirect to failure page }); }); + } else { + setTimeout(() => { + scrollToError(formValidityState); + }, 500); } return null; }; diff --git a/src/pages/GiftAid/utils/Utils.js b/src/pages/GiftAid/utils/Utils.js index 1bffcc8e..10f0f736 100644 --- a/src/pages/GiftAid/utils/Utils.js +++ b/src/pages/GiftAid/utils/Utils.js @@ -14,14 +14,15 @@ export const scrollToError = (state = {}) => { // Scroll to transactionId field / url parameter error message // if present if (state.urlTransactionId.valid === false) { - document.querySelector('#field-error--urlTransID').scrollIntoView('smooth'); + document.querySelector('#field-error--urlTransID').scrollIntoView({ behavior: 'smooth' }); } // Scroll to the first erroring field and focus on its input field const errorWrapper = document.querySelectorAll('.form__field--erroring')[0]; - const errorField = document.querySelectorAll('.form__field--erroring > div input')[0]; - if (errorWrapper !== undefined) { - errorWrapper.scrollIntoView('smooth'); - errorField.focus(); + if (errorWrapper) { + errorWrapper.scrollIntoView({ behavior: 'smooth' }); + setTimeout(() => { + document.querySelectorAll('.form__field--erroring > div input')[0].focus(); + }, 500); } };