Languages
[Edit]
EN

React - how to create dynamic header for the table

0 points
Created by:
cory
1486

In this article, we would like to show you how to create a dynamic header for the table in React.

To create a dynamic header we use two methods:

  • Object.keys() that takes the first object from the passed array and creates table (headers) filled with the object's properties,
  • map() method that renders <th> element for each element in headers table.

Note:

Remember that each element should have a unique key - it helps React optimally manage changes in the DOM. In below example we create counter to assign keys.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const tableStyle = {
  border: "1px solid black",
  borderCollapse: "collapse",
  textAlign: "center",
  width: "100%",
};

const tdStyle = {
  border: "1px solid #85C1E9",
  background: "white",
  padding: "5px",
};

const thStyle = {
  border: "1px solid #3498DB",
  background: "#3498DB",
  color: "white",
  padding: "5px",
};

const Header = ({ array }) => {
  let counter = 0;
  const headers = Object.keys(array[0] ?? {});
  return headers.map((x) => {
    ++counter;
    return (
      <th style={thStyle} key={counter}>
        {x}
      </th>
    );
  });
};

const App = () => {
  const students = [
    { id: 1, name: "Kate", age: 25, favFruit: "🍏" },
    { id: 2, name: "Tom", age: 23, favFruit: "🍌" },
    { id: 3, name: "Ann", age: 26, favFruit: "🍊" },
    { id: 4, name: "Jack", age: 21, favFruit: "🍒" },
  ];

  return (
    <div>
      <table style={tableStyle}>
        <tbody>
          <tr>
            <Header array={students} />
          </tr>
          {/* --- example data records --- */}
          {students.map(({ id, name, age, favFruit }) => (
            <tr key={id}>
              <td style={tdStyle}>{id}</td>
              <td style={tdStyle}>{name}</td>
              <td style={tdStyle}>{age}</td>
              <td style={tdStyle}>{favFruit}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );

References

Alternative titles

  1. React - how to create dynamic table header
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join