adrianhajdin / project_mern_memories

This is a code repository for the corresponding video tutorial. Using React, Node.js, Express & MongoDB you'll learn how to build a Full Stack MERN Application - from start to finish. The App is called "Memories" and it is a simple social media app that allows users to post interesting events that happened in their lives.
https://youtube.com/playlist?list=PL6QREj8te1P7VSwhrMf3D3Xt4V6_SRkhu
5.02k stars 1.84k forks source link

Automatic scroll to see the last comment scrolls the whole PostDetails page #102

Closed szaboako closed 2 years ago

szaboako commented 2 years ago

Hello,

In the CommentSection.jsx there is a part that is meant to make the comment section scroll if there is a new comment (handleClick last line) to make it visible. This function also scrolls the whole page. How can I make it to scroll only in the comment section?

import React, { useState, useRef } from 'react'
import { Typography, TextField, Button } from '@material-ui/core'
import { useDispatch } from 'react-redux'

import { commentPost } from '../../../actions/posts'
import useStyles from './styles'

const CommentSection = (post) => {
    const classes = useStyles()
    const dispatch = useDispatch()
    const commentsRef = useRef()
    const user = JSON.parse(localStorage.getItem('profile'))
    const [comments, setComments] = useState(post?.post?.comments)
    const [comment, setComment] = useState('')

    const handleClick = async () => {
        const finalComment = `${user.result.name}: ${comment}`

        const newComments = await dispatch(commentPost(finalComment, post.post._id))

        setComments(newComments)
        setComment('')

        commentsRef.current.scrollIntoView({ behavior: 'smooth' })
    }

    return (
        <div>
            <div className={classes.commentsOuterContainer}>
                <div className={classes.commentsInnerContainer}>
                    <Typography gutterBottom variant="h6">Comments</Typography>
                    {comments.map((comment, index) => (
                        <Typography key={index} gutterBottom variant="subtitle1">
                            <strong>{comment.split(': ')[0] + ':'}</strong>
                            {comment.split(':')[1]}
                        </Typography>
                    ))}
                    <div ref={commentsRef}/>
                </div>
                {user?.result?.name && (
                    <div style={{ width: '70%' }}>
                    <Typography gutterBottom variant="h6">Write a Comment</Typography>
                    <TextField 
                        fullWidth
                        rows={4}
                        variant="outlined"
                        label="Comment"
                        multiline
                        value={comment}
                        onChange={(e) => setComment(e.target.value)}
                    />
                    <Button style={{ marginTop: '10px' }} fullWidth disabled={!comment} variant="contained" color="primary" onClick={handleClick}>
                        Comment
                    </Button>
                    </div>
                )}
            </div>
        </div>
    )
}

export default CommentSection
szaboako commented 2 years ago

I have solved it, you have to put block: 'nearest' into the scroll line:

commentsRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' })