Search code examples
javascriptreactjsreact-virtualized

How can I implement infinite scrolling on a table using react-virualised?


I have been struggling with react-virtualised docs They have full-featured example tables. All I want is simple infinite scrolling for my table. Please if anyone can help. I just want to render my content when it's visible on the screen.
NOTE: I am not pulling the data from any API I have static data(an array of objects) saved into my local folder.
Please see a screenshot of my app below. enter image description here

Below is my code.

const renderRows = items.map((data, index) => {
    return (
      <tr
        className="table__row"
        key={data.id}
        onClick={() => onRowClick(data.id)}
      >
        <td style={{ marginRight: '2px' }}>
          <img
            onClick={(e) => {
              toggleStarSelect(e, data.id);
            }}
            src={Star}
            className="star"
            alt="star"
            style={{ padding: '2px' }}
          />

          {data['#']}
        </td>
        <td>
          <ImageLoadHandler
            isloaded={isloaded}
            handleImage={handleImage}
            data={data}
          />

          <span style={{ padding: '10px' }}>{data.Name}</span>
          <span
            style={{
              backgroundColor: 'lightgray',
              opacity: '0.5',
              fontSize: '13px',
            }}
          >
            {data.Symbol}
          </span>
        </td>
        <td>{data.Price}</td>
        <td>{data['1h']}</td>
        <td className={data['24h'] > 0 ? 'green' : 'red'}>
          {data['24h'] > 0 ? (
            <img className="arrowicon" src={SortUpGreen} alt="sort-up-green" />
          ) : (
            <img className="arrowicon" src={SortDownRed} alt="sort-down-red" />
          )}
          {data['24h']}%
        </td>
        <td>{data['7d']}</td>
        <td>{data['Mkt Cap']}</td>
        <td>{data['24h Vol']}</td>
        <td style={{ padding: '0', paddingRight: '8px' }}>
          <Suspense fallback={<div className="loading">loading...</div>}>
            <Graph data={data} idx={index} />
          </Suspense>
        </td>
      </tr>
    );
  });

  return (
    <div className="app">
      <header>
        <Header />
      </header>
      <table className="app__table">
        <thead className="app__tablehead">
          <tr>
            <th
              onClick={() => requestSort('#')}
              className={getClassNamesFor('#')} //returns ascending or descending
            >
              #
            </th>
            <th
              onClick={() => requestSort('Name')}
              className={getClassNamesFor('Name')}
            >
              Coin
            </th>
            <th
              onClick={() => requestSort('Price')}
              className={getClassNamesFor('Price')}
            >
              Price
            </th>
            <th
              onClick={() => requestSort('1h')}
              className={getClassNamesFor('1h')}
            >
              1h
            </th>
            <th
              onClick={() => requestSort('24h')}
              className={getClassNamesFor('24h')}
            >
              24h
            </th>
            <th
              onClick={() => requestSort('7d')}
              className={getClassNamesFor('7d')}
            >
              7d
            </th>
            <th
              onClick={() => requestSort('Mkt Cap')}
              className={getClassNamesFor('Mkt Cap')}
            >
              Mkt Cap
            </th>
            <th
              onClick={() => requestSort('24h Vol')}
              className={getClassNamesFor('24h Vol')}
            >
              24h Vol
            </th>
            <th className="nohover">Last 7 days</th>
          </tr>
        </thead>
        <tbody>{renderRows}</tbody>
      </table>
    </div>
  );

Solution

  • A working example of infinite scroll on a table element. Also a working a repl.

    import React, {useState, useEffect} from 'react';
    import './App.css';
    
    function App() {
      let items = [];
      for (let i = 0; i < 100; i++) {
        items.push({
          key: 'foo' + i,
          value: 'bar' + i,
        });
      }
    
      let dataTable = React.createRef();
      
      const [list, setList] = useState({
        itemsDisplayed: 20,
        data: items.slice(0, 20),
      });
    
      let onScroll = () => {
        let tableEl = dataTable.current;
        if (tableEl.scrollTop === (tableEl.scrollHeight - tableEl.offsetHeight)) {
          if (list.itemsDisplayed + 10 <= items.length) {
            setList({
              itemsDisplayed: list.itemsDisplayed + 10,
              data: items.slice(0, list.itemsDisplayed + 10),
            });
          }
        }
      };
    
      return (
        <div className="App">
          <table id="data-table" ref={dataTable} onScroll={onScroll}>
            <tbody>
              {list.data.map((item) => {
                return (
                  <tr key={item.key}>
                    {item.value}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      );
    }
    
    export default App;
    
    

    Also to mention, the problem of scrolling firing only once solved by this question. The point is to use React's built-in onScroll event.