Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

reactjs - How to render dynamic table in React

enter image description here

enter image description here

How will I do this kind of table in react? In each projects, there are employees and they have their corresponding positions. But in the project name (Column), on the second row, the 'Project A' should not be displayed.

  • Should not be like the second picture, where the 2nd and 3rd row still contains the project name. I want to exclude it and leave it blank.

Let say I sent a request from the server and it returned this json structure

[
    {
        "name": "Project A",
        "employees": [
            {
                "emp_name": "Employee 1",
                "emp_pos": "Position 1"
            },
            {
                "emp_name": "Employee 2",
                "emp_pos": "Position 2"
            }
        ]
    },

    {
        "name": "Project B",
        "employees": [
            {
                "emp_name": "Employee 5",
                "emp_pos": "Position 2"
            },
            {
                "emp_name": "Employee 3",
                "emp_pos": "Position 4"
            
            }
        ]
    }
]

I'm not sure, if the structure of my json file is correct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This answer is based on DBS answer with some modifications:

        <tbody>
          {data.map((project, projectIndex) => {
            return (
              <Fragment>
                {project.employees.map((employee, employeeIndex) => (
                  <tr>
                    <td>{employeeIndex === 0 ? project.name : null}</td>
                    <td>{employee.emp_name}</td>
                    <td>{employee.emp_pos}</td>
                  </tr>
                ))}
                {/* You can use projectIndex to skip the last empty row */}
                {data.length - 1 === projectIndex ? null : (
                  <tr>
                    <td colspan={3}>&nbsp;</td>
                  </tr>
                )}
              </Fragment>
            );
          })}
        </tbody>
      </table>

Codesandbox link


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...