React, Using Refs to scrollIntoView() doen't work on componentDidUpdate()
Ok it's been a while but I got it working in another project without the setTimeOut
function so I wanted to answer this question.
Since Redux pass the new updates through props, I used the componentWillRecieveProps()
method instead of componentDidUpdate()
, this allowes you a better control over the updated properties and works as expected with the scrollIntoView()
function.
class PhotoContainer extends React.Component {
componentWillReceiveProps(newProps) {
if (
this.props.navigation.sectionSelected !==
newProps.navigation.sectionSelected &&
newProps.navigation.sectionSelected !== ""
) {
this.focusDiv(newProps.navigation.sectionSelected);
}
}
focusDiv(section){
var scrolling = this[section]; //section would be 'theDiv' in this example
scrolling.scrollIntoView({ block: "start", behavior: "smooth" });//corrected typo
}
render() {
const totalList = [];
for(let i = 0; i < 300; i += 1) {
totalList.push(
<div key={i}>{`hello ${i}`}</div>
);
}
return (
<div >
{totalList}
<div ref={(el) => this.theDiv = el}>
this is the div I am trying to scroll to
</div>
</div>
)
};
}