DEV Community

Utsav Mavani
Utsav Mavani

Posted on

Load More button in a React.js

To implement a "Load More" button in a React.js application, you typically fetch additional data from an API or another data source when the button is clicked. Here's a basic example using the useState hook to manage the state of the displayed data and a counter to keep track of how many items to display.

Assuming you have an array of data and want to display a certain number of items initially, then load more when the button is clicked, you can follow these steps:

  1. Set up your component with state and a handler for the "Load More" button:
import React, { useState } from 'react';

const YourComponent = () => {
  // Your initial data
  const initialData = [
    // ... your data array
  ];

  // State to manage displayed data and load more button
  const [displayedData, setDisplayedData] = useState(initialData);
  const [visibleItemCount, setVisibleItemCount] = useState(5); // Change this as needed

  // Handler for the "Load More" button
  const handleLoadMore = () => {
    // Increase the visible item count (you can adjust this logic based on your requirements)
    setVisibleItemCount(prevCount => prevCount + 5);

    // Update displayedData with additional items
    setDisplayedData(initialData.slice(0, visibleItemCount + 5));
  };

  return (
    <div>
      {displayedData.map((item, index) => (
        // Render your data items here
        <div key={index}>{item}</div>
      ))}
      <button onClick={handleLoadMore}>Load More</button>
    </div>
  );
};

export default YourComponent;
Enter fullscreen mode Exit fullscreen mode

Customize the logic inside the handleLoadMore function based on your specific requirements. This example assumes a simple approach of increasing the visible item count and updating the displayed data accordingly.

Keep in mind that this is a basic example, and you might need to adapt it based on the structure of your data and the way you fetch additional items (e.g., from an API). If you're fetching data asynchronously, you might use useEffect and an asynchronous function within handleLoadMore to fetch and update the data.

Top comments (0)