I have a simple functional component. Its just a conditionally-rendered alert panel with an error message. The form is rather lengthy, so if there's an error, the panel renders but the user has scrolled to the point where the alert panel is off the screen. I want the page to scroll to the top whenever the component renders with an error. This should be window.scrollTo(0,0), but I cannot get that to work.
I know the window.scrollTo call is being made, because the "SCROLLING" message appears in the console. However, no scrolling actually happens; the window remains scrolled to the bottom of the form.
I tried a number of suggestions from other answers but I can't get this working; any help would be appreciated. Here's an abbreviated version of my component:
const OrderForm = ({
customer,
handleSubmit,
newCustomer,
omsAccountJwt,
showAccountSearch,
storeCode
}) => {
...
const orderState = useSelector(state => state.order);
useEffect(() => {
if (orderState.error) {
console.log('SCROLLING');
window.scrollTo(0, 0);
}
}, [orderState.error]);
...
return (
...
{orderState.error !== null && (
<AlertPanel
type="error"
text={`There was a problem processing the order: ${orderState.error}`}
/>
)}
<Formik
initialValues={{
selectedShippingAddress: defaultShippingIndex.toString(),
selectedPaymentMethod: defaultPaymentIndex.toString(),
storeCode
}}
onSubmit={(values, actions) => handleSubmit(order, values, actions)}
render={renderForm}
/>
...
)
}