DEV Community

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

Posted on • Updated 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.

Oldest comments (78)

Collapse
 
wanaphar profile image
PharWana

brother, I need help regarding the quilljs? can you help me out?

Collapse
 
abdulbasit313 profile image
Abdul Basit

Sorry, I never worked with quill. so no idea... if you want to know something related react I am here.

Collapse
 
guico33 profile image
guico33
key={Math.random()}

The key is supposed to be consistent between renders, random generated is a very bad solution.
Better use the array index if you don't have an unique identifier.

Collapse
 
abdulbasit313 profile image
Abdul Basit

hmmm... nice catch. fixed

Collapse
 
navasrifaya profile image
navas

hey man i have doubt in this how do i contact you?

Collapse
 
esinthe19 profile image
Esin G

Easy to follow! it helped me a lot. thanks!

Collapse
 
akash4111997 profile image
akash thoriya

How can I add buttons to each row [For example Buttons could be View, Edit, Delete ]

Collapse
 
abdulbasit313 profile image
Abdul Basit

Inside renderTableData method.

Collapse
 
abdulbasit313 profile image
Abdul Basit
Collapse
 
fazzysyed profile image
fazzysyed

how to add search and sorting in the table

Collapse
 
abdulbasit313 profile image
Abdul Basit

You can use ant design for that. By the way I have plan to update this article in couple of days.

Collapse
 
saltan1 profile image
saltan-1

How can I reach you regarding app development. Thanks

Collapse
 
arsalan1998 profile image
De_Codr

u can go with MUI Data Tables they are awesome

Collapse
 
ayeshaazam profile image
Ayesha

Hi,

Thanks for the Totorial, well explained!
Where Can I find the other features "like sorting, adding and removing data" you mentioned above.
Can I get the link of that Tutorial.
Thanks

Collapse
 
abdulbasit313 profile image
Abdul Basit
Collapse
 
micahbala profile image
Micah Bala

Thanks Abdul Basit for this tutorial, it helped me out, I have spend over 3 hours trying to render data from json on a table correctly. Thanks again.

Collapse
 
iam_pbk profile image
Bharathkumar

Suppose we want structure like "jsfiddle.net/cyril123/3n8xv3hL/" , how implement complex data with rowspan in react. Searched material-table but no luck it doesn't support complex data(material-table.com/).

Collapse
 
datmt profile image
Mạnh Đạt

Thanks for the tutorial. I'm a react beginner.

My question is, what if the number of column is unknown too?

Thanks again

Collapse
 
abdulbasit313 profile image
Abdul Basit • Edited

Here you go... you just need to change renderTableData function with below code. Let me know if it helps...

   renderTableData() {
      return this.state.students.map((student, index) => {
         let col = Object.keys(student)
         return (
            <tr key={student.id}>
               {col.map((val, index) => {
                  return <td key={index}>{student[col[index]]}</td>
               })}
            </tr>
         )
      })
   }
Collapse
 
datmt profile image
Mạnh Đạt

Thank you!

Collapse
 
hirupiyumika profile image
hirupiyumika

Thank you very much...!! It is very helpful.

Collapse
 
ronaldoperes profile image
Ronaldo Peres

Thank you,

How can I hide the first column?

Collapse
 
stephyswe profile image
Stephanie

So no follow up? : )

Collapse
 
alexjohan97 profile image
Alex Avelino Campos • Edited

please, how can i just show specific columns, for example in the exercise I just want to see the Name and the Age

Collapse
 
amisoliman70 profile image
Ahmed Soliman

Hi Abdul Basit, this is very helpful to me. Thank you!

How can I add rows to table dynamically? For example, if I create a table for a customer that have unknown number phone devices. So if a customer have 2 phone devices, we should have 2 rows, and if 3 phone devices, we should have 3 rows, etc.

Would you be able to show us how to add rows to a table?

Thanks
Ahmed

Collapse
 
coconutnegro profile image
Hendra Widjaja

You used too many ids. Be careful

Collapse
 
blup00 profile image
blup00

Thank you, great code, easy to follow!!

Collapse
 
bishwobhandari profile image
bishwobhandari

if i need to create a empty table of 10 rows where user can input data as form and submit the whole table to mobx store. how do i do it?

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