Home > Mobile >  Populating data on a table in React
Populating data on a table in React

Time:04-21

I have some nested data and i want to populate it in a table in react. As shown in the image, every method are in one row. How can i make a row for every method with its corresponding pages name? enter image description here

const methods = [{
  id: "1",
  name: 'First',
  pagesName: [{
    name: 'Login',
    message: 'Login Notification Message',
    messageType: 'Warning'
  },
  {
    name: 'Edit',
    message:'Edit Notification Message',
    messageType: 'Info'
  }]
},
{
 id: "2",
  name: 'Second',
  pagesName: [{
    name: 'Admin',
    message: 'Admin Notification Message',
    messageType: 'Info'
  },
  {
   name: 'Edit',
   message: 'Edit Notification Message',
   messageType: 'Warning'
}
]}
]

Table

<tbody>
   {methods.map((p, key) => {
       return (
           <tr>
           <td>{key}</td>
           <td>{p.name}</td>
           {p.pagesName.map((n, key) => {
           return (
              <>
              <td>{n.name}</td>
              <td>{n.message}</td>
              <td>{n.messageType}</td>
              </>
            )
            })}
           </tr>
           )})
           }
   </tbody>

CodePudding user response:

Use Array.map() like this: https://jsfiddle.net/Lc3m08dn/58/

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>PagesName</th>
            <th>Message</th>
            <th>messageType</th>
        </tr>
    </thead>
    {methods.map(method => (
        <tbody>
            <tr>
                <td rowspan={method.pagesName.length   1}>{method.id}</td>
                <td rowspan={method.pagesName.length   1}>{method.name}</td>
            </tr>
            {method.pagesName.map(page => (
                <tr>
                    <td>{page.name}</td>
                    <td>{page.message}</td>
                    <td>{page.messageType}</td>
                </tr>
            ))}
        </tbody>
    ))}
</table>
  • Related