How to add each element in a list to a new row in React table

Viewed 142

I'm super new to React and was wondering if there's a good and simple way to iterate through a list, and add each element in the list to a new row? For instance, for list:

name = ["A", "B", "C", "D"]

Eventually I want the table to have only one column and four rows:

Name
A
B
C
D
4 Answers

const data=['A','B','C','D'];

function Table() {
  return (
    <table>
       <thead>
         <tr>
           <th>row</th>
         </tr>
       </thead>
       <tbody>
       {
        data.map(item=>(<tr key={item}><td>{item}</td></tr>))
       }
       </tbody>
    </table>
  )
}


ReactDOM.render(<Table/>,document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

It is so easy. Needs to read about React.

You can map over your data when rendering.

return(
   <table>
   {name.map(rowName => 
       <tr key={rowName}>
           <td>{rowName}</td>
       </tr>
   } 
   </table>
)

You need to add a key to each component in the list so react knows when to rerender it.

Hope this helps!

In React you can use reuse your Javascript knowledge and that is really powerful. Array.prototype.map() is the function all you need.

This would also work:

const data = ["A", "B", "C", "D"]

const App = () => {
  return (
    <table>
      <tr>
        <th>Name</th>
      </tr>

      {data.map((item) => (
        <tr key={item}>
          <td>{item}</td>
        </tr>
      ))}
    </table>
  );
};

ReactDOM.render( < App / > , document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

return(
  <table>
    {name.map((it, index)=> 
      <tr key={index}>
        <td> <span> {index+1} <span/> {it} </td>
      </tr>
    } 
  </table>
)
Related