Home > Mobile >  React all comment options appear by one click
React all comment options appear by one click

Time:04-01

i have this code where I'm looping post array to extract comments



  const [commentOptions, setCommentOptions] = useState(false);

   return(
...

        {post.comments.map((comment) => (
          <div className="comments" key={comment._id}>
            <div className="commentUserImageAndUsername">
              <img
                className="commentUserImg"
                src={
                  comment.userId === users._id
                    ? users.profileImg || `${PF}/profile.jpg`
                    : null
                }
                alt="comment user "
              />
              {comment.userId === users._id ? users.firstname : null}
            </div>
            <div className="commentBody">{comment.body}</div>
            {user._id === comment.userId ? (
              <div
                className="commentOptionsMark"
                onClick={() => setCommentOptions(!commentOptions)}
              > - </div>
            ) : null}
            {commentOptions ? (
              <div className="commentOptions">
                <div className="deleteComment">Delete</div>
                <div className="editComment">Edit</div>
              </div>
            ) : null}
          </div>
        ))}
...
)

for every comment i have the hyphen mark -, if i click it, it will set the commentOptions state to true, therefore the commentOptions div will appear, which contains 2 options delete comment and edit comment, the problem with this is that if i click the hyphen mark for one comment, the commentOptions div will appear for every comment, like if there are 5 comments and every comment has its own options, i can control the appearance of commentOptions div for every comment by just one click, this is not what i want, i want to show one div for every comment hyphen - on click, not all of them at once, like every comment on its own, how to fix that?

CodePudding user response:

store the clicked comments id for controlling:

const [shownCommentId, setShownCommentId] = useState('');


{user._id === comment.userId ? (
      <div
         className="commentOptionsMark"
         onClick={() => setShownCommentId(comment._id)}
      > - </div>
) : null}

then control the id in your map:

{shownCommentId === comment._id ? (
      <div className="commentOptions">
          <div className="deleteComment">Delete</div>
          <div className="editComment">Edit</div>
      </div>
 ) : null}
  • Related