I'm trying to clear input when i press <button onClick={addComment} className='add-btn'>+</button> Missing "key" prop for element in iterator react/jsx-key
import React, { useContext, useState } from 'react';
import ContentHeader from './PatientHeader';
import { PatientContext } from '../App';
const moment = require('moment');
const ContentInfo = () => {
const { selectedPatient, comments, setComments } = useContext(PatientContext);
const [comment, setComment] = useState('');
const commentInput = React.createRef();
const addComment = (e: any) => {
const date = moment();
setComments([...comments, { comment: commentInput.current.value, date: date }]);
e.preventDefault();
setComment('');
};
const handleChange = (e: any) => setComment(e.target.value);
return (
<div className='content'>
<ContentHeader />
<div className='info'>
<div className='comments'>
<div>
<p>
<h3 className='comments-text'>Comments:</h3>
</p>
<ul>
{comments.map(c =>
<li>
<div className='new-comment'>
<div>
<strong>{moment(c.date).format('ll')}</strong>
</div>
<div>
{c.comment}
</div>
</div>
</li>
)}
</ul>
</div>
<div className='create-commentInput'>
<input value={comment} ref={commentInput} onChange={handleChange}
className='form-control' type="text"/>
<button onClick={addComment} className='add-btn'>+</button>
</div>
</div>
</div>
</div>
);
}
The following line is throwing the error, and I cannot figure out why:
(e: any)
const addComment = (e: any) => {
const date = moment();
setComments([...comments, { comment: commentInput.current.value, date: date }]);
e.preventDefault();
setComment('');
};
How can I prevent this error from appearing?