Use React's ref feature

This commit is contained in:
Sonny Bakker 2023-07-15 20:58:51 +02:00
parent fedeed15c5
commit a4f5a7bdd7
2 changed files with 25 additions and 25 deletions

View file

@ -34,8 +34,11 @@ class PostItem extends React.Component {
ruleUrl = `${this.props.feedUrl}/${rule.id}/`; ruleUrl = `${this.props.feedUrl}/${rule.id}/`;
} }
{
/* TODO: figure out why this is called up to three times */
}
return ( return (
<li className="posts__item" data-id={post.id}> <li className="posts__item" ref={this.props.forwardedRef}>
<h5 <h5
className={titleClassName} className={titleClassName}
title={post.title} title={post.title}

View file

@ -11,29 +11,21 @@ import PostItem from './PostItem.js';
class PostList extends React.Component { class PostList extends React.Component {
handleIntersect = ::this.handleIntersect; handleIntersect = ::this.handleIntersect;
lastPostRef = null;
observer = null; observer = null;
lastPost = null;
callCount = 0;
constructor(props) { constructor(props) {
super(props); super(props);
this.lastPostRef = React.createRef();
const observerOptions = { root: null, rootMargin: '0px', threshold: 0 }; const observerOptions = { root: null, rootMargin: '0px', threshold: 0 };
this.observer = new IntersectionObserver(this.handleIntersect, observerOptions); this.observer = new IntersectionObserver(this.handleIntersect, observerOptions);
} }
componentDidUpdate() { componentDidUpdate() {
const lastPost = [...this.props.postsByType] if (this.lastPostRef.current) {
.reverse() this.observer.observe(this.lastPostRef.current);
.find(post => post.read === false);
if (lastPost && (!this.lastPost || lastPost.id != this.lastPost.id)) {
const observeTarget = document.querySelector(
`.posts__item[data-id="${lastPost.id}"]`
);
this.lastPost = lastPost;
this.observer.observe(observeTarget);
} }
} }
@ -65,17 +57,22 @@ class PostList extends React.Component {
render() { render() {
const postItems = this.props.postsByType.map((item, index) => { const postItems = this.props.postsByType.map((item, index) => {
return ( const isLastItem = this.props.postsByType.length - 1 == index;
<PostItem const defaultProps = {
key={index} key: index,
post={item} post: item,
selected={this.props.selected} selected: this.props.selected,
feedUrl={this.props.feedUrl} feedUrl: this.props.feedUrl,
subredditUrl={this.props.subredditUrl} subredditUrl: this.props.subredditUrl,
timelineUrl={this.props.timelineUrl} timelineUrl: this.props.timelineUrl,
timezone={this.props.timezone} timezone: this.props.timezone,
/> };
);
if (isLastItem && !item.read) {
return <PostItem {...defaultProps} forwardedRef={this.lastPostRef} />;
} else {
return <PostItem {...defaultProps} />;
}
}); });
if (isEqual(this.props.selected, {})) { if (isEqual(this.props.selected, {})) {