admin管理员组

文章数量:1287828

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

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

Share Improve this question asked Apr 27, 2021 at 12:58 Technical knowledgeTechnical knowledge 2222 silver badges11 bronze badges 1
  • You can add id to an element and use href to that particular id. – Bikki Mahato Commented Apr 27, 2021 at 13:13
Add a ment  | 

2 Answers 2

Reset to default 6

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'
});

This line of code works for me

window.scrollTo(0, 0);

本文标签: javascriptscroll to the top of page in reactjsStack Overflow