Auto scroll to anchor tag element in react using componentDidUpdate

蹲街弑〆低调 提交于 2021-02-08 10:02:33

问题


  • My URL

https://abc1234.com/users#api-doc

  • HTML

    <div className={parent}>
        <div className={child}>
            {someContent}
            <a id="api-doc">Hello API</a>
        </div>
    </div>

I am writing the page in ReactJS. I need to implement a way so that the page should auto-scroll down to the Hash i.e. api-doc but somehow it's not auto-scrolling on page load (very first time).

I tried a workaround which is like this


    componentDidUpdate(){
        let id = this.props.history.location.hash.replace("#", "");
        let element = document.getElementById(id);
        setTimeout(() => {
            if (element) {
                element.scrollIntoViewIfNeeded(true);
            }
        }, 200);
    }

It's working but I am looking for a better way to achieve the same

In other words, I do not want to use setTimeOut.

I added setTimeOut cause I found that document.getElementById(id) is giving null (very first time), I am assuming that somehow componentDidUpdate is running before the entire render. I have also used dangerouslySetInnerHTML .

来源:https://stackoverflow.com/questions/64224547/auto-scroll-to-anchor-tag-element-in-react-using-componentdidupdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!