Reputation:
I am trying to implement an infinity scroll but facing the "TypeError: Cannot read property 'offsetTop' of null". I have attached my implementation below. I am new to react and I would love to get your suggestion for better implementation.
loadMore = () => {
this.setState({page: this.state.page + 1})
this.loadUser();
};
handleScroll = () => {
var lastLi = document.querySelector("div.container-fluid > div:last-child");
var lastLiOffset = lastLi.offsetTop + lastLi.clientHeight;
var pageOffset = window.pageYOffset + window.innerHeight;
if (pageOffset > lastLiOffset) {
this.loadMore();
}
};
componentWillMount() {
this.loadUser();
this.scrollListener = window.addEventListener("scroll", e => {
this.handleScroll(e);
});
}
render() {
if(this.state.dataStatus == false) {
return (
<div>
<Header />
<h4>Loading</h4>
</div>
);
} else {
return(
<div>
<Header />
<PostContainer posts={this.state.data}/>
</div>
);
}
}
}
PostContainer Code -> it traverses through the array and calls Renderpost
class PostContainer extends Component {
constructor(props) {
super(props);
}
render() {
const menu = this.props.posts.map(post => {
return (
<RenderPost post={post}/>
)
});
return (
<div className="container-fluid">
<div className="row justify-content-center">
{menu}
</div>
</div>
);
}
}
RenderPost code
return(
<div className="post-holder shadow-sm p-3 mb-4 bg-white rounded" key={this.props.post.id}>
</div>
);
Upvotes: 0
Views: 96
Reputation: 203323
document.querySelector
can return null
if there are no matches. You should definitely check if a valid HTMLElement
was returned before accessing attributes on it.
Also, I think the selector "div.container-fluid > div:last-child"
will more likely match the <div className="row justify-content-center">
div as it is the direct child of "div.container-fluid"
.
Instead, it looks like you want to target the last post that is rendered by this inner div. Using an id
may make this easier
<div className="row justify-content-center" id="post-container">
{menu}
</div>
Then update the handler
var lastLi = document.querySelector("div#post-container > div:last-child");
Upvotes: 1
Reputation: 417
try to learn about ref
, in React.js we don't use querySelector
Upvotes: 0