How to build a dynamic table with React

Dynamic rendering in React is enabled by states embedded inside the JSXJavaScript XML of a functional component. Let's say that we have a state title that is supposed to contain the text for a <h1> tag. We will declare the state as follows:

const [title, setTitle] = useState('<Your_Title_Here>');

Then, we'll embed it into the JSX containing the <h1> tag as follows:

<h1>{title}</h1>

Now, whenever the value of title updates, the page would be re-rendered to reflect the changes in the <h1> tag.

The application below attaches an onClick method to the <h1> tag to change the state of the title state, consequently updating the text on the page:

Dynamic table rendering in React

The same principles as in the previous example can be used to render a dynamic table in React. Instead of storing a string in a state variable, we'll store an array:

const [tableData, setTableData] = useState([]);

Then, we'll embed the array in the JSX of the functional component to produce the table structure according to the data inside the array. Finally, we'll add buttons to append more data to this array or clear the array entirely.

The code snippet below presents the complete React application that utilizes the chance package to generate random user data to be appended in a dynamic table:

  • Lines 4–17: Defines the createRandomUsers function that generates and returns the specified number of user data (in the default case 5) in an array.

  • Line 20: Initializes the state tableData with an empty array that would be used to render the dynamic table.

  • Lines 22–27: Defines the method handleGenerateUsers that utilizes the createRandomUsers to generate new users and appends them to the current tableData state.

  • Lines 27–29: Defines the method handleClearUsers that sets the tableData state to an empty array.

  • Lines 33–35: Creates a heading and two buttons. The first button linked with the handleGenerateUsers function, whereas the latter is linked with the handleClearUsers function.

  • Lines 36–59: Creates a table with a header and a body. The header contains cells specifying User ID, Name, Email and Date of Birth. The body of the table, defined on lines 45–58, iterates over the tableData state using the map method. For each element, it creates a table row with cells corresponding to the header with appropriate values.

Copyright ©2024 Educative, Inc. All rights reserved