Reputation: 185
I have a react.js useState that I set to false by default. So, what I want to do is to change it to true when an edit button is clicked. It is actually array of comments that I mapped and displayed individually. I would like the user to be able to edit the comment he or she made and clicked the edit button specifically for that comment. Here are my codes:
const [updateComment, setUpdateComment] = useState(false)
<h5 className='users-comment'>Users comments</h5>
{comments.map((singleComment, _id)=>{
return(
<>
{updateComment ?
<div className='comment-div' key={_id}>
<textarea className='comment-wrapper' type='text' placeholder='Share your comment'
onChange={(e) => setCommentDescription(e.target.value)}
></textarea>
<button className='comment-btn'onClick={handleCommentUpdate}>Update Post</button>
</div>
:
<div className='displayed-comments'>
<div className="commentPic">
<img className="user-pics" src={PF + singleComment.author.profilePicture} alt="" />
</div>
<div className="comment-info">
<div className="comment-author-div">
<div className='comment-author-date-info'>
<h4 className="comment-author">{singleComment.author.username}</h4>
<p className="comment-date">{new Date(singleComment.createdAt).toDateString()}
</p>
</div>
<div className="comment-edit-delete-div">
<i className="singlePostIcon fas fa-edit" onClick={() => setUpdateComment(true)} ></i>
<i className="singlePostIcon far fa-trash-alt" ></i>
</div>
</div>
<p className="comment-content">{singleComment.commentdescription}</p>
</div>
</div>
}
</>
)
})}
The edit button is this line of code:
<i className="singlePostIcon fas fa-edit" onClick={() => setUpdateComment(true)} ></i>
But with this current line of codes, once I click on that edit button, it affects all the comments that are on display. I just want it to affect only the comment that I clicked on, so that I can edit that particular comment. Thank you as you.
Upvotes: 0
Views: 395
Reputation: 706
You need to put the state in a single Comment
component, so every component have a specific state.
OR you can set the _id
of the edited comment in the state. like this:
<i
className="singlePostIcon fas fa-edit"
onClick={() => setUpdateComment(_id)} // <===
/>
and instead of
{updateComment ?
<div className='comment-div' key={_id}>
...
do it like that:
{updateComment === _id ?
<div className='comment-div' key={_id}>
...
Upvotes: 1