4

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}
      />
    ...
    )
}

2 Answers 2

1

It probably has something to do with the structure of your state or how you're updating your state in handleSubmit. Take a look at this working codesandbox and see if it helps

https://codesandbox.io/s/bitter-platform-kov7s

const Scroller = props => {
  const [orderState, setOrderState] = React.useState({ error: false });
  console.log({ orderState });

  React.useEffect(() => {
    if (orderState.error) {
      console.log("SCROLLING");
      window.scrollTo(0, 0);
    }
  }, [orderState.error]);

  function handleClick() {
    setOrderState({ error: true });
  }

  return <button onClick={handleClick}>Scroll up</button>;
};
Sign up to request clarification or add additional context in comments.

Comments

1

Check your layout and see if your content div is set to height: 100vh; with overflow: auto;. That makes your window full height at all times, so there isn't anything to scroll.

I had something similar, and changed that div to be min-height: 100vh and now the scroll works, and the footer stays at the bottom.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.