Skip to content
Advertisement

scroll to the top of page in reactjs

I am designing the registration page in Reactjs .and I am doing manual validation. now what I want is after clicking onSubmit, the page should scroll to the top to show all errors in the validation.I tried but failed to achieve this.is there anyone who will help me

Advertisement

Answer

If you task is to scroll to errors rather than scrolling to top, you can try this.

import React { useRef } from 'react';

const Component = () => {
    const errorRef = useRef(null);

    const onSubmitHandler = () => {
        ...
        errorRef.current.scrollIntoView();
    }

    return (
        ...
        <div ref={errorRef} className='error-container'>
            ...
        </div>
        ...
    );
}

Note: Still you want to try scroll to top you can try this.

window.scrollTo(0,0);

or

window.scrollTo({
    top: 0,
    left: 0,
    behavior: 'smooth'
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement