React Displaying Data In Tables Or Lists Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    10 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of React Displaying Data in Tables or Lists

React Displaying Data in Tables or Lists

1. Understanding State and Props

Before diving into the specifics of rendering tables or lists, it's crucial to have a firm grasp of React’s state and props.

  • State (useState): This is local to the component and can be modified. State changes trigger a re-render of the component.
  • Props (props): These are passed from a parent component to a child component. Props are immutable, i.e., they should not be changed within the component.

2. Rendering Lists

Rendering lists in React involves mapping an array of data to an array of JSX elements.

  • Array.map(): This function is used to iterate over an array and return a new array.
    const data = ['Apple', 'Banana', 'Cherry'];
    
    function FruitList({ fruits }) {
      return (
        <ul>
          {fruits.map((fruit, index) => (
            <li key={index}>{fruit}</li>
          ))}
        </ul>
      );
    }
    
    <FruitList fruits={data} />
    
  • Key Prop: When rendering lists, it's essential to provide a unique key prop for each list item. This helps React identify which items have changed, are added, or are removed.

3. Rendering Tables

Rendering data in tables follows a similar approach to lists.

  • Table Structure: Tables typically consist of <table>, <thead>, <tbody>, <tr>, <th>, and <td> tags.

    const users = [
      { id: 1, name: 'John', email: 'john@example.com' },
      { id: 2, name: 'Jane', email: 'jane@example.com' },
      { id: 3, name: 'Doe', email: 'doe@example.com' },
    ];
    
    function UserTable({ users }) {
      return (
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user) => (
              <tr key={user.id}>
                <td>{user.name}</td>
                <td>{user.email}</td>
              </tr>
            ))}
          </tbody>
        </table>
      );
    }
    
    <UserTable users={users} />
    

4. Conditional Rendering

Data might not always be available or might change based on user interactions. Conditional rendering is crucial for displaying data dynamically.

  • Example: Conditionally rendering a loading indicator while data is being fetched.
    function UserInfo({ user, isLoading }) {
      if (isLoading) return <p>Loading...</p>;
      return (
        <div>
          <h1>{user.name}</h1>
          <p>{user.email}</p>
        </div>
      );
    }
    

5. Styling Tables and Lists

Styling tables and lists can enhance the user experience. CSS is a common way to style these components.

  • CSS Modules: This allows for scoped CSS and keeps your styles organized.
  • Styled Components: This library enables writing CSS for your components in JavaScript.

6. Dynamic Data Handling

Dynamic data handling involves fetching data from an API and updating the component state accordingly.

  • useEffect Hook: This hook is used to fetch data when the component mounts or when some state or prop changes.
    import { useState, useEffect } from 'react';
    
    function DataFetchingComponent() {
      const [data, setData] = useState([]);
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
        fetch('https://api.example.com/data')
          .then((response) => response.json())
          .then((data) => {
            setData(data);
            setLoading(false);
          })
          .catch((error) => console.error(error));
      }, []);
    
      if (loading) return <p>Loading...</p>;
    
      return (
        <ul>
          {data.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      );
    }
    

7. Pagination and Sorting

Large datasets can be overwhelming to display at once. Pagination and sorting are useful features to manage large lists or tables.

  • Pagination:
    • Show only a subset of data at a time.
    • Provide controls (e.g., "Next", "Previous") to navigate through the data.
  • Sorting:
    • Allow users to sort data by one or more columns.
    • Implement sorting logic in the component or use a third-party library.

8. Accessibility

Ensuring tables and lists are accessible is crucial for inclusivity.

  • ARIA Attributes: Use ARIA attributes like aria-label to describe elements.
  • Semantic HTML: Use semantic HTML tags to ensure screen readers understand the structure and purpose of your data.

9. Performance Considerations

Rendering large lists or tables can be resource-intensive. Optimization techniques include:

  • Memoization: Use React.memo to prevent unnecessary re-renders.
  • Virtualization: Implement virtualization libraries like react-window to only render items visible in the viewport.

10. Third-Party Libraries

Several third-party libraries can simplify the process of creating complex tables or lists.

  • Material-UI: Provides styled components for tables and lists.
  • React Table: A powerful library for building customizable tables.
  • React Virtualized: Helps in rendering large datasets efficiently.

By following these guidelines and understanding the key concepts, you can effectively display data in tables or lists in React, ensuring both performance and user experience are optimized.

Important Keywords:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement React Displaying Data in Tables or Lists

Table of Contents

  1. Setup a React Project
  2. Fetch Data
  3. Create Functional Components
  4. Render Data in a List
  5. Style the List
  6. Render Data in a Table
  7. Style the Table
  8. Add Interactivity

1. Setup a React Project

First, you should set up a new React project. You can do this using Create React App:

npx create-react-app react-table-list-example
cd react-table-list-example
npm start

This will start a local development server with your empty React application at http://localhost:3000.


2. Fetch Data

Assume we have an API that fetches user data (name and email) which we will use to display in our table and list. In practice, this could be any API endpoint.

For demonstration purposes, we'll use the JSONPlaceholder API, which provides fake user data.


3. Create Functional Components

Let's make a simple functional component named Users that will fetch and display the data.

// src/components/Users.js
import React, { useEffect, useState } from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(data => setUsers(data))
            .catch(error => console.error('Error fetching users:', error));
    }, []);

    return (
        <div>
            <h1>Users</h1>
            {/* Table and List components will go here */}
        </div>
    );
};

export default Users;

Import this component in our main App.js file.

// src/App.js
import React from 'react';
import Users from './components/Users';

function App() {
  return (
    <div className="App">
      <Users />
    </div>
  );
}

export default App;

4. Render Data in a List

Now let's render the fetched user data in a simple unordered list.

// src/components/Users.js
import React, { useEffect, useState } from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(data => setUsers(data))
            .catch(error => console.error('Error fetching users:', error));
    }, []);

    return (
        <div>
            <h1>Users List</h1>
            <ul>
                {users.map(user => (
                    <li key={user.id}>
                        {user.name} - {user.email}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default Users;

5. Style the List

It's always good to add some styling. We'll add basic CSS to make our list more readable.

Add a style.css file inside your src directory.

/* src/style.css */
.App {
    font-family: Arial, sans-serif;
    padding: 20px;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    background: #f9f9f9;
    padding: 10px;
    margin: 5px 0;
    border-radius: 5px;
}

Then, import this CSS file in your App.js or Users.js.

// src/App.js
import React from 'react';
import './style.css';
import Users from './components/Users';

function App() {
  return (
    <div className="App">
      <Users />
    </div>
  );
}

export default App;

6. Render Data in a Table

Next, let's display the same user data in a table format.

// src/components/Users.js
import React, { useEffect, useState } from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(data => setUsers(data))
            .catch(error => console.error('Error fetching users:', error));
    }, []);

    return (
        <div>
            <h1>Users Table</h1>
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    {users.map(user => (
                        <tr key={user.id}>
                            <td>{user.name}</td>
                            <td>{user.email}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default Users;

7. Style the Table

We'll add some additional CSS to style our table.

Update the style.css file.

/* src/style.css */
.App {
    font-family: Arial, sans-serif;
    padding: 20px;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    background: #f9f9f9;
    padding: 10px;
    margin: 5px 0;
    border-radius: 5px;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
}

th,
td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

th {
    background-color: #f2f2f2;
}

tr:hover {
    background-color: #f5f5f5;
}

8. Add Interactivity

Let's make our user listing a bit interactive by allowing users to sort the table by name.

We'll add a sort functionality and a button to toggle sorting order.

// src/components/Users.js
import React, { useEffect, useState } from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);
    const [sortOrder, setSortOrder] = useState('asc');

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(data => setUsers(sortUsers(data)))
            .catch(error => console.error('Error fetching users:', error));
    }, []);

    const sortUsers = (data) => {
        return data.sort((a, b) => {
            if (sortOrder === 'asc') {
                return a.name.localeCompare(b.name);
            } else {
                return b.name.localeCompare(a.name);
            }
        });
    };

    const handleSort = () => {
        const newOrder = sortOrder === 'asc' ? 'desc' : 'asc';
        setSortOrder(newOrder);
        setUsers(sortUsers(users));
    };

    return (
        <div>
            <h1>Users List & Table</h1>

            {/* List Component */}
            <ul>
                {users.map(user => (
                    <li key={user.id}>
                        {user.name} - {user.email}
                    </li>
                ))}
            </ul>

            {/* Table Component */}
            <button onClick={handleSort}>Toggle Sort Order ({sortOrder})</button>
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    {users.map(user => (
                        <tr key={user.id}>
                            <td>{user.name}</td>
                            <td>{user.email}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default Users;

Final Result

Your Users component should now look like this:

// src/components/Users.js
import React, { useEffect, useState } from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);
    const [sortOrder, setSortOrder] = useState('asc');

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(data => setUsers(sortUsers(data)))
            .catch(error => console.error('Error fetching users:', error));
    }, []);

    const sortUsers = (data) => {
        return data.sort((a, b) => {
            if (sortOrder === 'asc') {
                return a.name.localeCompare(b.name);
            } else {
                return b.name.localeCompare(a.name);
            }
        });
    };

    const handleSort = () => {
        const newOrder = sortOrder === 'asc' ? 'desc' : 'asc';
        setSortOrder(newOrder);
        setUsers(sortUsers(users));
    };

    return (
        <div>
            <h1>Users List & Table</h1>

            {/* List Component */}
            <ul>
                {users.map(user => (
                    <li key={user.id}>
                        {user.name} - {user.email}
                    </li>
                ))}
            </ul>

            {/* Table Component */}
            <button onClick={handleSort}>Toggle Sort Order ({sortOrder})</button>
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    {users.map(user => (
                        <tr key={user.id}>
                            <td>{user.name}</td>
                            <td>{user.email}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default Users;

And, your App.js file should look like this:

// src/App.js
import React from 'react';
import './style.css';
import Users from './components/Users';

function App() {
  return (
    <div className="App">
      <Users />
    </div>
  );
}

export default App;

Explanation

  • Fetching Data: Using useEffect to fetch the data when the component mounts.
  • State Management: Using useState to keep track of users and sortOrder.
  • Sorting Logic: Implementing a simple function sortUsers to sort the array based on the current sort order.
  • Rendering in List/Table: Mapping through the stateful users array to render individual elements as list items (<li>) or table rows (<tr>).
  • Interactivity: Adding a button to toggle between ascending and descending order and re-render the sorted list/table.

Running the Application

Run npm start to ensure everything works as expected:

npm start

Navigate to http://localhost:3000, and you should see a list of users and a table displaying the same users. The table has a button to toggle the sorting order based on the user names.


Top 10 Interview Questions & Answers on React Displaying Data in Tables or Lists

1. How do you display a list of items in React?

Answer: In React, you can display a list of items using the map() function to create a new array of items, and then render it inside a component. You should also provide a unique key for each element in the list to help React identify which items have changed, are added, or are removed. Example:

const items = ['Apple', 'Banana', 'Cherry'];

function ItemList() {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li> // Use index as a key as a last resort
      ))}
    </ul>
  );
}

2. What are the best practices for using keys in React lists?

Answer: Best practices for using keys in React lists include:

  • Use unique IDs generated by a backend service or a library.
  • Use UUIDs if IDs are not available.
  • Avoid using the array index as a key if the order of items may change as this can negatively impact performance and may lead to unexpected behavior.
  • Ensure keys are strings.

3. How can you display paginated data in a React table?

Answer: To display paginated data in a React table, you can use libraries like React Table or manage pagination manually. Here's a simple example using manual pagination:

import React, { useMemo, useState } from 'react';

function PaginatedTable({ items }) {
  const [currentPage, setCurrentPage] = useState(0);
  const itemsPerPage = 5;
  const currentItems = useMemo(() => {
    return items.slice(currentPage * itemsPerPage, (currentPage + 1) * itemsPerPage);
  }, [currentPage, items]);

  return (
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
        {currentItems.map((item) => (
          <tr key={item.id}>
            <td>{item.name}</td>
            <td>{item.age}</td>
          </tr>
        ))}
      </tbody>
    </table>
    <div>
      <button onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 0}>
        Previous
      </button>
      <button onClick={() => setCurrentPage(currentPage + 1)} disabled={currentPage >= Math.ceil(items.length / itemsPerPage) - 1}>
        Next
      </button>
    </div>
  );
}

4. How do you sort data in a React table?

Answer: You can sort data in a React table by managing the sort state in your component. When the sorting button is clicked, update the state to reflect the new order. Here’s an example:

import React, { useState } from 'react';

function SortableTable({ data }) {
  const [sortConfig, setSortConfig] = useState({ key: 'name', direction: 'ascending' });

  const sortedData = useMemo(() => {
    let sortableItems = [...data];
    if (sortConfig !== null) {
      sortableItems.sort((a, b) => {
        if (a[sortConfig.key] < b[sortConfig.key]) {
          return sortConfig.direction === 'ascending' ? -1 : 1;
        }
        if (a[sortConfig.key] > b[sortConfig.key]) {
          return sortConfig.direction === 'ascending' ? 1 : -1;
        }
        return 0;
      });
    }
    return sortableItems;
  }, [data, sortConfig]);

  const requestSort = (key) => {
    let direction = 'ascending';
    if (sortConfig.key === key && sortConfig.direction === 'ascending') {
      direction = 'descending';
    }
    setSortConfig({ key, direction });
  };

  return (
    <table>
      <thead>
        <tr>
          <th onClick={() => requestSort('name')}>Name</th>
          <th onClick={() => requestSort('age')}>Age</th>
        </tr>
      </thead>
      <tbody>
        {sortedData.map((item) => (
          <tr key={item.id}>
            <td>{item.name}</td>
            <td>{item.age}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

5. How can you display nested data in a React table?

Answer: To display nested data in a React table, you need to parse the nested object properties and render them accordingly. You can use recursion if the data depth is unknown:

function renderNestedData(obj) {
  return Object.keys(obj).map((key) => {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      return <div key={key}>{key}: {renderNestedData(obj[key])}</div>;
    } else {
      return <div key={key}>{key}: {obj[key]}</div>;
    }
  });
}

function NestedTable({ items }) {
  return (
    <table>
      <thead>
        <tr>
          <th>Details</th>
        </tr>
      </thead>
      <tbody>
        {items.map((item) => (
          <tr key={item.id}>
            <td>{renderNestedData(item)}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

6. How can you search through data in a React table?

Answer: To implement search functionality in a React table, add a search input field and filter the data based on the input:

import React, { useState } from 'react';

function SearchableTable({ items }) {
  const [searchTerm, setSearchTerm] = useState('');

  const filteredItems = items.filter(item => (
    item.name.toLowerCase().includes(searchTerm.toLowerCase())
  ));

  return (
    <div>
      <input
        type="text"
        placeholder="Search by name"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
          </tr>
        </thead>
        <tbody>
          {filteredItems.map((item) => (
            <tr key={item.id}>
              <td>{item.name}</td>
              <td>{item.age}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

7. How can you handle large datasets efficiently in React?

Answer: Handling large datasets efficiently in React involves techniques such as lazy loading, windowing, and memoization:

  • Lazy Loading: Load data in chunks as the user scrolls.
  • Windowing: Only render items visible in the viewport, using libraries like react-window or react-virtualized.
  • Memoization: Use useMemo to prevent unnecessary recalculations of large datasets.

8. How can you implement checkboxes in a React table?

Answer: To implement checkboxes in a React table, manage the checked state in your component and update it when checkboxes are toggled:

import React, { useState } from 'react';

function CheckboxTable({ items }) {
  const [selectedItems, setSelectedItems] = useState([]);

  const toggleSelection = (id) => {
    setSelectedItems((prev) => {
      if (prev.includes(id)) {
        return prev.filter((itemId) => itemId !== id);
      } else {
        return [...prev, id];
      }
    });
  };

  return (
    <table>
      <thead>
        <tr>
          <th>Select</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        {items.map((item) => (
          <tr key={item.id}>
            <td>
              <input
                type="checkbox"
                checked={selectedItems.includes(item.id)}
                onChange={() => toggleSelection(item.id)}
              />
            </td>
            <td>{item.name}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

9. How can you use React Table or other libraries for better tables?

Answer: React Table is a feature-complete library designed to handle complex tables. Here’s a simple usage example:

import React from 'react';
import { useTable } from 'react-table';

function ReactTableExample({ columns, data }) {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({ columns, data });

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render('Header')}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              ))}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

// Example usage:
const data = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
];

const columns = [
  {
    Header: 'Name',
    accessor: 'name',
  },
  {
    Header: 'Age',
    accessor: 'age',
  },
];

function App() {
  return <ReactTableExample data={data} columns={columns} />;
}

10. How can you style tables in React components?

Answer: You can style tables in React components using CSS or CSS-in-JS libraries like styled-components. Here’s an example using plain CSS:

You May Like This Related .NET Topic

Login to post a comment.