Reputation: 75
I want to scroll automatically to the bottom of a page (component) after visiting the page (render the component) or updating it. I have tried with refs and react-scroll library but no success. Here is my code:
Using refs:
class CommentsDrawer extends Component {
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth" });
};
render() {
const { show, closeDrawer } = this.props;
let drawerClasses = styles.drawer;
if (show) {
drawerClasses = `${styles.drawer} ${styles.open}`;
}
return (
<div className={drawerClasses}>
<div>
<CommentsDrawerHeader closeDrawer={closeDrawer} numOfComments={mockedData.length} />
</div>
<CommentsList data={mockedData} />
{/* TODO: Reply functionality is just a mockup for this task scope. To be fully implemented in the integration task. */}
<CommentInput />
<div ref={(el) => { this.messagesEnd = el; }} />
</div>
);
}
}
Upvotes: 0
Views: 122
Reputation: 75
The solution was to create the reference in the constructor of the component. I have made the implementation in the child component which renders the comments.
mport React, { Component, createRef } from "react";
import { array, func, boolean } from "prop-types";
import Comment from "../Comment/Comment";
import styles from "./CommentsList.scss";
class CommentsList extends Component {
static propTypes = {
// eslint-disable-next-line react/forbid-prop-types
data: array.isRequired,
sendReply: func,
deleteReply: func,
show: boolean
};
static defaultProps = {
sendReply: () => {},
deleteReply: () => {},
show: true
};
constructor(props) {
super(props);
this.bottomRef = createRef();
}
componentDidMount() {
this.scrollToBottom();
}
shouldComponentUpdate() {
if (!this.props.show) {
this.scrollToBottom();
}
}
scrollToBottom = () => {
this.bottomRef.current.scrollIntoView({ behavior: "smooth" });
};
render() {
const { data, sendReply, deleteReply } = this.props;
return (
<div className={styles.comments__list}>
{data.map(el => (
<Comment
// eslint-disable-next-line no-underscore-dangle
key={el._id}
// eslint-disable-next-line no-underscore-dangle
id={el._id}
by={el.by}
jobTitle={el.jobTitle}
timestamp={el.at}
comment={el.comment}
// eslint-disable-next-line no-undef
replyTo={!_.isUndefined(el.replyTo) && el.replyTo}
origin={el.origin}
sendReply={sendReply}
deleteReply={deleteReply}
/>
))}
<div ref={this.bottomRef} />
</div>
);
}
}
export default CommentsList;
Upvotes: 1