How to create customized dynamic table in React

6 points
Created by:
Dirask Community

Hi everyone!┬á👋┬á😊

Last week I had a problem with creating a dynamic table in React, so I thought that maybe someone will find this solution helpful.

Effect of this short post:

React - customized dynamic table
React - customized dynamic table

I took several steps in the solution below:

  1. I created a dynamic table based on array,
  2. Each table consists of a header and some data records,
  3. The header is fixed and keeps the same amount of columns,
  4. While creating records I used map() function to convert array items into React elements. 

Remember┬áthat each element should have a unique key┬á🗝´ŞĆ┬ábecause┬áit helps┬áReact┬áoptimally manage changes in the DOM.┬áSuch a key may be┬áfor example┬áthe┬áid┬áassigned to each element of the table.

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 App = () => {
  	const students = [
        { id: 1, name: 'Tom',  age: 25, favFruit: '🍏' },
        { id: 2, name: 'Adam', age: 43, favFruit: '🍌' },
        { id: 3, name: 'Mark', age: 16, favFruit: '🍊' },
        { id: 4, name: 'John', age: 29, favFruit: '🍒' }
    return (
        <table style={tableStyle}>
              <th style={thStyle}>Id</th>
              <th style={thStyle}>Name</th>
              <th style={thStyle}>Age</th>
              <th style={thStyle}>Favourite Fruit</th>
            {{ 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>

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


Check out┬áthis article┬áif you want to read┬ámore about dynamic tables.┬á😊


ReactJS - Blog posts

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.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé