Search code examples
reactjsdatatablereact-hooksreact-component

React-Hooks: How to create reusable data table component?


In my application, I need to reuseable data table component. Where I can change table-header & table-body with dynamic content.

 <table className="table table-hover">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Publish Date</th>
                    </tr>
                </thead>
                <tbody>
                    {data &&
                        data.map(item => (
                            <tr key={item.id}>
                                <td>{item.id}</td>
                                <td>{item.image}</td>
                                <td>{item.title}</td>
                                <td>{item.publishDate}</td>
                            </tr>
                        ))}
                </tbody>
            </table>

Solution

  • See if this works! https://stackblitz.com/edit/react-ie2rt6

    import React from "react";
    
    const Table = ({ headers, data }) => {
      return (
        <div>
          <table>
            <thead>
              <tr>
                {headers.map(head => (
                  <th>{head}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {data.map(row => (
                <tr>
                  {headers.map(head => (
                    <td>{row[head]}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    };
    
    export default Table;