0

I am building an app and users can add comments, I can't get the div to auto scroll to the bottom so when the user comments their latest comment doesn't show unless they scroll as I have overflow-y set to scroll. How could I implement this in React please?

Comments div

<div className = 'comments'>
          {item.comments.map((comment,index) => {
          return <h6 key = {index}><span className ='comment-name'> {comment.postedBy.name} </span> {comment.text}</h6>}
</div>

comments css

.comments {
  max-height: 20vh;
  overflow-y: scroll;
  padding-left: 1rem;
}

Form submit code

 <form onSubmit = {(e) => {
                            e.preventDefault()
                            makeComment(e.target[0].value, item._id)
                            e.target[0].value = null }
</form>
        
Dan Wilstrop
  • 355
  • 1
  • 4
  • 12

1 Answers1

1

Every library I tried didn't have the desired effect as I have multiple scrollable divs on the page and I couldn't get it to work.

I ended up using the css

display: flex;
flex-direction: column-reverse;

This had the effect but the data was then displayed backwards so this little line solved that issue before it was mapped through to display the comments

item.comments.slice(0).reverse().map((function...))

Little bit of a 'bodge' but the end result is perfect

Dan Wilstrop
  • 355
  • 1
  • 4
  • 12