Search code examples
javascriptreactjsscrollbootstrap-modal

React modal scroll to top


I have a modal with a long form in my react application. So when I submit the form I am showing the validation messages from the server on top of the form. So the user has to scroll to the top to view the messages. So I want to automatically scroll to the top when the message appears. So I added the below code in the submit handler function. But it is not working.

setAddModalErrorMsg([{ msg: res.data.msg, type: "error" }])
                    window.scrollTo({
                        top: 0,
                        left: 0,
                        behavior: "smooth"
                      });

Solution

  • The other answers showed how you can scroll the modal to the top, and that is the generally accepted way of achieving this, though, I want to show you how to scroll the "Message" into view, regardless of whether it's on the top or not.

    You would also need to create a ref to where you display your message and use the scrollIntoView functionality to scroll the modal to your validation message.

    import React, { useRef } from 'react';
    
    const Modal = () => {
      const validationMessageRef = useRef();
    
      const setAddModalErrorMsg = () => {
        // scrolls the validation message into view, and the block: 'nearest' ensures it scrolls the modal and not the window
        validationMessageRef.current?.scrollIntoView({ block:'nearest' });
      }
    
      return (
        <div>
          <div ref={validationMessageRef}>
            // your validation message is displayed here
          </div>
    
          // rest of your modal content here
        </div>
    
      )
    }