2

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
2
  • I don't see this.setSlotCardRef define anywhere. Maybe this.setSlotCardRef is this.setItemRef ? Commented Oct 29, 2019 at 9:40
  • sorry, copied by mistake, should be setItemRef Commented Oct 29, 2019 at 22:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.