Deivydas Kinderis
Deivydas Kinderis

Reputation: 23

How to merge React TableCells inside a map function?

So I am trying to create a table with material-ui where rows of w1 and w2 are merged vertically, but I can't seem to find a solution. Using rowSpan when hardcoding table manually works just fine, but when I use it inside map function it creates 4 columns with merged rows of the same element. I need to map data because there is going to be lots of rows in that table and hardcoding all rows is not reasonable.

Any type of suggestion to resolve this?

<TableBody>
    {data.data.map((row, i) => (
        <TableRow key={row.i}>
            <TableCell className={classes.fontEditable} component="th" scope="row">
                {row.x1}
            </TableCell>
            <TableCell className={classes.fontEditable} align="right">
                {row.x2}
            </TableCell>
            <TableCell rowSpan={4} className={classes.fontEditable} align="right">
                {row.w1}
            </TableCell>
            <TableCell rowSpan={4} className={classes.fontEditable} align="right">
                {row.w2}
            </TableCell>
            <TableCell className={classes.font} align="right">
                {row.t}
            </TableCell>
        </TableRow>
    ))}
</TableBody>

Expected outcome

Expected outcome

Actual outcome

Actual outcome

Upvotes: 2

Views: 3645

Answers (1)

Joe Fathalla
Joe Fathalla

Reputation: 76

problem: it creates the w1 and w2 cell in each row because of the map function

solution: you can do an if condition for the w1 and w2 print for the first only as the following

<TableBody>
{data.data.map((row, i) => (
    <TableRow key={row.i}>
        <TableCell className={classes.fontEditable} component="th" scope="row">
            {row.x1}
        </TableCell>
        <TableCell className={classes.fontEditable} align="right">
            {row.x2}
        </TableCell>
        {i === 0? 
           <TableCell rowSpan={4} className={classes.fontEditable} align="right">
             {row.w1}
           </TableCell>
           <TableCell rowSpan={4} className={classes.fontEditable} align="right">
             {row.w2}
           </TableCell>
        :null}
        <TableCell className={classes.font} align="right">
            {row.t}
        </TableCell>
    </TableRow>
))}

Upvotes: 6

Related Questions