Issue
Lets say I have component "Post" which holds multiple components "Comment". I want to make that application scrolls down on comment with that anchor when I enter URL like this:
/post/:postId/#commentId
I have already working postId route /post/:postId
I tried to implement it with react-hash-link npm package but it's not working as intended.
Every comment has it's own ID which is set on component, like this:
<div class="post">
<div class="post-header">
<div class="post-header-avatar">
SOME TEXT
</div>
<div class="post-header-info">
SOME TEXT
</div>
</div>
<div class="post-content">
<span>POST CONTENT</span>
</div>
<div class="post-likers-container">
<div class="post-likers-header label">People who like this post</div>
<div class="post-likers">
SOME TEXT
</div>
</div>
<div class="post-comments">
<div class="comments ">
<div class="comments-all label">Comments</div>
<div class="comments">
<div class="comment" id="5d27759edd51be1858f6b6f2">
<div class="comment-content">
COMMENT 1 TEXT
</div>
</div>
<div class="comment" id="5d2775b2dd51be1858f6b720">
<div class="comment-content">
COMMENT 2 TEXT
</div>
</div>
<div class="comment" id="5d2775ecdd51be1858f6b753">
<div class="comment-content">
COMMENT 3 TEXT
</div>
</div>
</div>
</div>
</div>
</div>
So for example if I open URL like:
/post/postId/#5d2775ecdd51be1858f6b753
I want to open page of post and that it scrolls down to the comment with # anchor.
Is there any way to implement this?
Solution
I managed to find simple solution for my use case, without creating refs for comments, passing them, etc. Since my hierarchy of components is like this:
Post
--> render componentComments
Comments
--> render multiple componentsComment
with props data passed fromPost
In Post
component I created function:
scrollToComment= () => {
let currentLocation = window.location.href;
const hasCommentAnchor = currentLocation.includes("/#");
if (hasCommentAnchor) {
const anchorCommentId = `${currentLocation.substring(currentLocation.indexOf("#") + 1)}`;
const anchorComment = document.getElementById(anchorCommentId);
if(anchorComment){
anchorComment.scrollIntoView({ behavior: "smooth" });
}
}
}
Then I render Comments
like this:
<Comments limit={limit} post={post} scrollToComment={this.scrollToComment} />
In Comments
I generate comments after some sorting like this:
{sortedComments.map((comment, i) => <Comment key={i} {...comment} scrollToComment={this.props.scrollToComment}/> )}
and finally in Comment
component I execute scrollToComment
in ComponentDidMount()
:
if(this.props.scrollToComment)
this.props.scrollToComment(this.props._id);
After that when I go to some URL I get nice smooth scrolling to the comment specified in hash part of URL.
I tried @Christopher solution but it didn't worked for me.
Answered By - SaltyTeemooo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.