Search code examples
javascripthtmlreactjsweb-frontenddom-manipulation

How do I list elements in the table with React?


I am new to React. How can I list elements from two different arrays in two columns using "map" function?

state = {
  dates: ["2000", "2001", "2002"],
  cases: ["1", "2", "3"]
}

render() {
  return (
    <thead>
      <tr>
        <th>Date</th>
        <th>Cases</th>
      </tr>
    </thead>
    <tbody>
      {this.state.dates.map(el => 
        <tr>
          <td>{el}</td>
        </tr>
      )} // I want to list elements from "cases" array like this but in the second column
    </tbody>
  )
}

Solution

  • Quick and Easy Solution: Not recommended

    If you're going to always assume that dates and cases will always be the same length then you could do this:

    {this.state.dates.map((el, index) => (
      <tr>
        <td>{this.state.dates[index]}</td>
        <td>{this.state.cases[index]}</td>
      </tr>
    ))}
    

    This method makes use of the index parameter of the map function. Then you can access the array at the specific index mentioned.


    Recommended Solution:

    The usual practice is to keep your data grouped per record.

    Using your example, use a structure like this:

    state  = {
      records: [
        { date: '2000', caseId: '1' },
        { date: '2001', caseId: '2' },
        { date: '2002', caseId: '3' }
      ],
    }
    

    Then implement it like this:

    {this.state.records.map(({ date, caseId }) => (
      <tr>
        <td>{date}</td>
        <td>{caseId}</td>
      </tr>
    ))}
    

    I'm using caseId instead of case because case is a reserved word in JavaScript for switch statements.