DEV Community

Cover image for An easy way to create a customize dynamic table in react js
Abdul Basit
Abdul Basit

Posted on • Edited on

An easy way to create a customize dynamic table in react js

In this article I will try to teach how to create a dynamic table in react.
Ya I know its quite simple, but this tutorial is for beginners and a beginner should know how to get this kind of stuff done.

I am assuming you know how to create a project and how javascript classes work. If you dont't, read this article first.

Lets begin
We have data in the form of array of objects just like APIs. You can use API too.

Lets create a simple component and store the data in the state.



import React, { Component } from 'react'

class Table extends Component {
   constructor(props) {
      super(props) //since we are extending class Table so we have to use super in order to override Component class constructor
      this.state = { //state is by default an object
         students: [
            { id: 1, name: 'Wasif', age: 21, email: 'wasif@email.com' },
            { id: 2, name: 'Ali', age: 19, email: 'ali@email.com' },
            { id: 3, name: 'Saad', age: 16, email: 'saad@email.com' },
            { id: 4, name: 'Asad', age: 25, email: 'asad@email.com' }
         ]
      }
   }

   render() { //Whenever our class runs, render method will be called automatically, it may have already defined in the constructor behind the scene.
      return (
         <div>
            <h1>React Dynamic Table</h1>
         </div>
      )
   }
}

export default Table //exporting a component make it reusable and this is the beauty of react


Enter fullscreen mode Exit fullscreen mode

We have 4 students with id, name, age and email address. Since our table will be dynamic so it doesn't matter if we have 4 or 100 students.

For Table Data

Now we want to print out students data in the Dom. We often use map function in react to itearate over array.
Lets write a separate function for table data and calling it in our render method. This approach will make our code cleaner and easier to read.



   renderTableData() {
      return this.state.students.map((student, index) => {
         const { id, name, age, email } = student //destructuring
         return (
            <tr key={id}>
               <td>{id}</td>
               <td>{name}</td>
               <td>{age}</td>
               <td>{email}</td>
            </tr>
         )
      })
   }

   render() {
      return (
         <div>
            <h1 id='title'>React Dynamic Table</h1>
            <table id='students'>
               <tbody>
                  {this.renderTableData()}
               </tbody>
            </table>
         </div>
      )
   }


Enter fullscreen mode Exit fullscreen mode

You may have noticed our renderTableData method only returns tr not the tr inside table. Since tr alone can not be a child of div so we have to wrap tr inside table and tbody in our render method.

table header

We are done with table data, a table should have a header too. Lets work on header.

For Table Header

Now we will write another method for table header.



   renderTableHeader() {
      let header = Object.keys(this.state.students[0])
      return header.map((key, index) => {
         return <th key={index}>{key.toUpperCase()}</th>
      })
   }

   render() {
      return (
         <div>
            <h1 id='title'>React Dynamic Table</h1>
            <table id='students'>
               <tbody>
                  <tr>{this.renderTableHeader()}</tr>
                  {this.renderTableData()}
               </tbody>
            </table>
         </div>
      )
   }


Enter fullscreen mode Exit fullscreen mode

Object.Keys gives us all the keys of students in the form of array and we stored it in a variable header. So we can iterate the header (array) using map method.
You may think why we don't use forEach, it does the same. The reason is when we want to return something as result we use map method, while forEach doesn't return anything, it just iterates over array's elements.

Styling

Lets add little bit styling in our table to make it look good



#title {
  text-align: center;
  font-family: arial, sans-serif;
}

#students {
  text-align: center;
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  border: 3px solid #ddd;
  width: 100%;
}

#students td, #students th {
  border: 1px solid #ddd;
  padding: 8px;
}

#students tr:nth-child(even){background-color: #f2f2f2;}

#students tr:hover {background-color: #ddd;}

#students th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: center;
  background-color: #4CAF50;
  color: white;
}


Enter fullscreen mode Exit fullscreen mode

table header

That's all, we are done with our basic table. In next article we will add some features in table, like sorting, adding and removing data. Here is the codepen link of the project.

Here you can read How To Create An Editable Text Field In Table Using ReactJS.

Latest comments (78)

Collapse
 
kerenren profile image
kerenren

with

element, it's not possible to add border radius and box shadow etc.

any solution to achive this?
Collapse
 
more03625 profile image
Rahul More

How can I add CRUD BTns in each row.
Also how can I status coloum with proper colours, like for active green and inactive red

Collapse
 
hakimasa profile image
HakimAsa

nice article. However, your renderTableCell method should be dynamic as well, similar to what you've done with header.
the inner return statement should be like what you see in the screenshot

Collapse
 
salimeh1364 profile image
Salimeh1364

hi abdul ,
in advance thanks for your clear code, i have a question
i have one array that include fore example 10 field that each field has many information , i want to show each field in one table ,it means if i have 10 field in array show in 10 table saparately . thanks alot

Collapse
 
parasbuda profile image
Parasbuda

Can u give some example for implementing the dynamic table for multiple tables

Collapse
 
diraskreact profile image
Dirask-React • Edited

Hello 👋
Thanks for sharing! 👍
Recently I created a solution for dynamic table using functional components, so if you are interested you can go and check it. 😊
dev.to/dirask/react-how-to-create-...

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Nice Post But how do someone Put this type of Object in a Table ? {
Australia: 1
Burma: 2
Canada: 3
China: 1
Cyprus: 1
Egypt: 3
France: 2
Greece: 1
Iran (Persia): 1
Isle of Man: 1
Japan: 1
Norway: 1
Russia: 4
Singapore: 1
Somalia: 1
Thailand: 4
Turkey: 2
United Arab Emirates: 1
United Kingdom: 8
United States: 28}

Collapse
 
shahirdev profile image
Shahir Hussaini

Object.keys(yourObject).map(obj => (


{obj}
{yourObject[obj]}

))

use this method it will solve your problem.

Collapse
 
abdulbasit313 profile image
Abdul Basit

You can do two things.

  1. Write the logic that changes this object into array or array of objects.
  2. If you have hard coded data then write it in this way countries : [ { country : 'US', id: 1, } ] Something like this
Collapse
 
femi_akinyemi profile image
Femi Akinyemi

I think I will go with the first option. But will I be able to add the unique name and ID then

Thread Thread
 
abdulbasit313 profile image
Abdul Basit

Yes you can further spread the object or array. Read about spread operator

Thread Thread
 
femi_akinyemi profile image
Femi Akinyemi

Alright Thanks

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Can someone please help me with this

Collapse
 
shantnu02 profile image
SHANTANU SINGH

if i just show Id, name only and when this datatable made nd in that if i click 2 nd no.
of id then it goes to next page nd show full data??????

Collapse
 
faizanmustafa profile image
FaizanMustafa

Thanks ton. This post is really helpful for me.

Collapse
 
muhammadaligabol profile image
Ali

Very helpful article.

But I want to fetch data from an API instead of this Array of object, can you tell me how?

Collapse
 
abdulbasit313 profile image
Abdul Basit

Read my other article

Some comments may only be visible to logged-in visitors. Sign in to view all comments.