Scroll to element in an array after rendering using React ref callback

Viewed 499

I would like to use ref callback to scroll to an element in an array after rendering. Depending on state, it will scroll to different element based on this.state.scrollToId. But I think the callback in the below code was not triggered before componentDidUpdate

P.S. Item is a customised component.

I have tried componentDidMount too.

class A extends React.Component{
//... 
    state = { scrollToId: null}
    scrollToMyRef = (myRef) =>{
        window.scrollTo(0, myRef.current.offsetTop)
    }

    constructor(props) {
        super(props)
        this.itemRefs = {};
        this.setItemRef = (element, id) => {
            this.itemRefs[id] = element;
        }
    }

    componentDidUpdate(){
        if (this.state.scrollToId){
                scrollToMyRef(this.itemRefs[this.state.scrollToId])
    }
    render(){
        return (
            <div>
                {
                    this.state.aList.map((item)=>{
                        return (
                                <Item ref={(element) => {this. setItemRef(element, item.id)}}
                                </Item>
                        )

                    })
                }
            </div>)
     }
}
  • Expected: based on the state, the page would scrolled to the corresponding element
  • Actual: itemRef[id] was undefined, and throw exception on scrollToMyRef
0 Answers
Related