Search code examples
reactjslifecycle

How to scroll to a component after it's shown on the page on React?


I need to scroll to the component after it gets rendered to the page (I am using React scroll to component). The component itself is not shown by default (the component will be rendered when example_shown is true). Something like this:

{props.example_shown && (
    <ExtraComponent />
)}

and inside the ExtraComponent, I give ref={(section) => { this.ExtraComponent = section }}. I tried to call scrollToComponent inside componentDidMount() but this.ExtraComponent returns to null. How can I scroll to position? Ideally componentDidMount() should work right? I have been reading about the life cycle and couldn't solve it. What am I missing?


Solution

  • FOUND THE ANSWER!

    componentDidMount() {
        var elementWhereIwantToScrollTo = ReactDOM.findDOMNode(this)
        scrollToComponent(elementWhereIwantToScrollTo, { offset: 0, align: 'middle', duration: 500, ease: 'inCirc' })
    }
    

    then on the render, I specify:

    <CardBox
       ref={(section) => { this.elementWhereIwantToScrollTo = section }}
    >