How To Create A Table in ReactJS
How To Create A Table in ReactJS
When displaying data in an organized style in web applications, tables are
a popular component. Using the strength of JSX and JavaScript, you can
quickly construct dynamic and interactive tables in ReactJS. The process
of making a table in ReactJS will be covered in this post, along with some
best practices. In this article, we will create a simple table in React.js just
like you would create in a normal HTML project.
Prerequisites: The pre-requisites for this project are:
React
Functional Components
JavaScript ES6
HTML Tables & CSS
Creating a React application:
Step 1: Create a react application by typing the following command in the
terminal.
npx create-react-app react-table
Javascript
import './App.css';
function App() {
return (
<div className="App">
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<tr>
<td>Anom</td>
<td>19</td>
<td>Male</td>
</tr>
<tr>
<td>Megha</td>
<td>19</td>
<td>Female</td>
</tr>
<tr>
<td>Subham</td>
<td>25</td>
<td>Male</td>
</tr>
</table>
</div>
);
In the above example, we just simply used the HTML table elements
which are <table>, <tr>, <th>, and <td> elements.
Example 2: Now let us see how we can dynamically render data from an
array. Instead of manually iterating over the array using a loop, we can
simply use the inbuilt Array.map() method. The Array.map()
method allows you to iterate over an array and modify its elements using
a callback function. The callback function will then be executed on each
of the array’s elements. In this case, we will just return a table row on each
iteration.
Filename: App.js
Javascript
import './App.css';
// Example of a data array that
const data = [
function App() {
return (
<div className="App">
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
return (
<tr key={key}>
<td>{val.name}</td>
<td>{val.age}</td>
<td>{val.gender}</td>
</tr>
})}
</table>
</div>
);
Filename: App.css Now, let’s edit the file named App.css to style the table.
CSS
.App {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
table {
width: 800px;
height: 200px;
th {
td {
text-align: center;