score:2

Accepted answer

when you add a new comment to the comment array, you are adding it as an array of one object. this results in your comment array having a nested array, however your rendering of the comment array expects objects inside of it.

you probably want to rewrite the comment code to create an object and not an array of a single object:

let comment = {
    name: username,
    comment: usercomment
};

score:0

that id because you are contacting the wrong thing in your function commentwrite. you are appending array inside an array. the solution will be :

  const commentwrite = (event) => {
    event.preventdefault();
    let comment = [
      {
        name: `${username}`,
        comment: `${usercomment}`
      }
    ];
    setcommentarray([...commentarray, ...comment]);
    console.log(commentarray);
  };

or you can do one thing is make comment as json object

  const commentwrite = (event) => {
    event.preventdefault();
    let comment = {
        name: `${username}`,
        comment: `${usercomment}`
      };
    setcommentarray([...commentarray, comment]);
    console.log(commentarray);
  };

score:0

here is the solution for you

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]);
 
  };


  const comments = commentarray.map((comment, index) => {
    return (
      <tr key={index}>
            <td>{comment[0].name}</td>
            <td>{comment[0].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;

Related Query