Instructions for creating dynamic data tables with ReactJS

Tram Ho

  • In this article, I will show you how to create a table with dynamic data in ReactJS .
  • I know it’s quite simple for some of you, but this tutorial is for beginners so they know how to do them

Begin:

  • We have data as an array of API-like objects. You can also use the API.
  • First create simple component and store data in ** state **

  • Here we have 4 students with id, name, age and email address. Because of our table with dynamic data, it doesn’t matter if we have 4 or 100 students …

Create data for tbody

  • Now we want to print students data in the DOM. We often use the map function in react to iterate over arrays (like a for loop).
  • Write a new function and call it out using the render method. This way we will see the code more compact and easier to read

  • You may have noticed our renderTableData method returns tr instead of tr within the table. Since tr cannot be a child of a div , we have to wrap tr inside the tbody

Create data for the header

  • Now we write a new function for the header as above

  • Object.Keys provides us with all the student keys as arrays and we have stored them as header variables. Because we can repeat the header by using map ()
  • You might think why we don’t use forEach, it does the same. The reason is when we want to be map () because it will return a new array. So we use the map () method, while forEach doesn’t return anything, it just iterates over the elements. of the array.

Result:

  • That’s all, we have finished with simple tables. Demo link

     

Conclude

Share the news now

Source : Viblo