I'm trying to solve kind of simple problem: when component is loaded, i need to scroll it to the bottom. But i've wasted ton of hours trying to solve it. I've tried a lot of different ways (scrollIntoView, scrollTop, scrollBy, etc...) but none of them can't do it. Url below is a link to fiddle where i have a simple component and i need Message to be shown. The problem is that i have to scroll about 10 pixels by myself. I would really appreciate if you help me to solve this problem.
class Hello extends React.Component {
componentDidMount() {
const elem = ReactDOM.findDOMNode(this.refs.test);
if (elem) {
elem.scrollIntoView(false);
}
}
render() {
return (
<div>
<div className="test"
ref="test">
Hello {this.props.name}
</div>
<div>Message</div>
</div>
)
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
You placed the ref
attribute on the wrong place.
Move it one level up in order to catch the whole component, including the "Message" text.
So, basically:
class Hello extends React.Component {
// ...
render() {
return (
<div ref="test">
<div className="test">
Hello {this.props.name}
</div>
<div>Message</div>
</div>
)
}
}
Here's a working jsfiddle demo , forked from yours.
class Hello extends React.Component {
// ...
componentDidUpdate() {
this.scrollDiv.scrollIntoView(false);
}
render() {
return (
<div
ref={(el) => {this.scrollDiv = el}}
>
<div className="test">
Hello {this.props.name}
</div>
<div>Message</div>
</div>
)
}
}
You should scroll only when the component is loaded into DOM filled with all props.
export default class Hello extends React.Component {
constructor(props,context){
super(props,context);
this.isAlreadyLoaded = false;
}
componentWillReceiveProps(nextProps) {
let scrollToElement = document.getElementById("scroll-element");
if (scrollToElement && !isAlreadyLoaded){
this.isAlreadyLoaded = true;
scrollToElement.scrollIntoView(true);
}
}
render(){
return {....}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.