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.
- Researches done:
- Using 'ref' as array in React
- https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
- How to assign refs to multiple components
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 onscrollToMyRef
this.setSlotCardRefdefine anywhere. Maybethis.setSlotCardRefisthis.setItemRef?setItemRef