Search code examples
reactjslogicreact-component

Need help in logic building for react table


I have a very little problem, but I am new developer and learning react for the very first time, finding it very hard to solve it.

Problem:

I have a component named Table, I am rendering another component named TableRow inside this by iterating over other items. In table row component I am rendering rows. I have data rows something like this:

1: [a]
2: [a,b]
3: [a]

I want output something like this

1  a
2  a
   b
3  a

I am able to achieve output like this

1  a
2  a
2  b
3  a

but finding it very hard to get the exact output. In table row component, I am just iterating over items and displaying it, I have to include a login in which I can check if header for 2 is already available, don't put it, and insert only data part. How to achieve that. Any help will be appreciated. Thank you.

data: [
{
  header: header
  items: [1]
},
{
   header: header2,
   items: [1,2]
 },
{
   header: header3,
    items: [1,2]
 }
 ]

SampleCode:

<Table>
    this.props.data.map(obj => {
        return <NewComponent header = {obj.header} items = {obj.items} />
    })
</Table>

<NewComponent> 
    this.props.items.map(item=> {
        <TableRow> 
                <th> {this.props.header} </th>
                <tb> {item} </tb>
        </TableRow>
    })
</NewComponent>

Current Output:

1 1
2 1
2 2 
3 1

I want

1  1
2  1
   2
3  1

Any help will be appreciated.


Solution

  • Just conditionally render the header value if its the first pass

    <Table>
        this.props.items.map( (item, idx), => 
            <TableRow> 
                <TableHeader>{idx === 0 ? this.props.header : ''}<TableHeader>
                <TableBody>body>item<TableBody>
            </TableRow>
        )
    </Table>
    

    Edit

    heres an example following your update.

    const Table = (props) => {
        const { data } = props;
        return (
          <table>
            <tbody>
              {data.map((row, idx) => (
                <TableRow header={row.header} items={row.items} />
              ))}
            </tbody>
          </table>
        );
      }
    }
    
    const TableRow = ({ header, items }) => {
      return items.map((item, idx) => (
        <tr>
          <td>{idx === 0 ? header : " "}</td>
          <td>{item}</td>
        </tr>
      ));
    };
    

    Heres a simple example to play with