I'm trying to create a small comment box using react.
My user will input into a name and comment box.
This gets saved as an array and added to the existing state array.
The updated data gets mapped into a table and displayed.
I can see the updated arrays in my console, but nothing is displayed. What have I done wrong?
import '../App.css';
import React, { useState } from 'react';
function App(props) {
const [userName, setUserName] = useState("");
const [userComment, setUserComment] = useState("");
const [commentArray, setCommentArray] = useState([]);
const commentWrite = (event) => {
event.preventDefault();
let comment = [
{
name: `${userName}`,
comment: `${userComment}`
}
];
setCommentArray([...commentArray, comment]);
console.log(commentArray);
};
const comments = commentArray.map((comment, index) => {
return (
<tr key={index}>
<td>{comment.name}</td>
<td>{comment.comment}</td>
</tr>
)
});
return (
<>
<div className="wrapper">
<header className="App-header">
<h1>Comment box</h1>
</header>
<div className="commentInput">
<form >
<input type="text" placeholder="Name" required onChange={e => setUserName(e.target.value)}></input>
<input type="text" placeholder="Comment" required onChange={e => setUserComment(e.target.value)}></input>
<button type="submit" onClick={(event) => { commentWrite(event, userName, userComment) }} >Post</button>
</form>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
{comments}
</tbody>
</table>
</div>
</>
);
}
export default App;