Zenixo
Zenixo

Reputation: 877

How to use scrollintoview inside useeffect ( Cannot read properties of null (reading 'scrollIntoView') )

I need to set my webPage from beginning to start. So I write code like this.

function BasicDetails() {

    React.useEffect(()=>{
        scrollView();
    }, []);

    function scrollView() {
        document.getElementById('main-root').scrollIntoView({behavior: 'smooth'});
    }
    return (
        <Nav>
            <div id="main-root" style={{scrollBehavior: 'smooth'}}>
                <div>
                    <Header pageTitle={'Shop Settings'}/>
                    <Button
                        onClick={saveBasicDetails}
                        variant="contained"
                        id='save'
                        className={classes.saveButton}>
                        SAVE
                    </Button>
                </div>

                <BasicDetailsData style={{scrollBehavior: 'smooth'}} ref={childRef}/>
            </div>
        </Nav>
    );
}

But When I Tried to run my code, I have an error TypeError: Cannot read properties of null (reading 'scrollIntoView') So I tried many times but can't find the error. I am a new student for react, so. I don't know much about it. Anyone can help me with this...I really need your help..thank you.

Upvotes: 0

Views: 3878

Answers (1)

Vibran
Vibran

Reputation: 80

I tried this out and this is how I got it to work:

function scrollView() {
    const mainRoot = document.getElementById("main-root");
    mainRoot.scrollIntoView({ behavior: "smooth" });
  }

Upvotes: 4

Related Questions