Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use window.scrollTo with react/material UI?

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}
      />
    ...
    )
}
like image 362
boing Avatar asked Oct 17 '25 14:10

boing


2 Answers

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>;
};
like image 137
Barryman9000 Avatar answered Oct 19 '25 03:10

Barryman9000


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.

like image 36
Brenda Avatar answered Oct 19 '25 04:10

Brenda