How to build a dynamic table with React
Dynamic rendering in React is enabled by states embedded inside the 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
createRandomUsersfunction that generates and returns the specified number of user data (in the default case5) in an array.Line 20: Initializes the state
tableDatawith an empty array that would be used to render the dynamic table.Lines 22–27: Defines the method
handleGenerateUsersthat utilizes thecreateRandomUsersto generate new users and appends them to the currenttableDatastate.Lines 27–29: Defines the method
handleClearUsersthat sets thetableDatastate to an empty array.Lines 33–35: Creates a heading and two buttons. The first button linked with the
handleGenerateUsersfunction, whereas the latter is linked with thehandleClearUsersfunction.Lines 36–59: Creates a table with a header and a body. The header contains cells specifying
User ID,Name,EmailandDate of Birth. The body of the table, defined on lines 45–58, iterates over thetableDatastate using themapmethod. For each element, it creates a table row with cells corresponding to the header with appropriate values.
Free Resources