React - limit and show loop list item

0 votes
42 views
added Jan 29 in React by lcjr First Warrant Officer (11,850 points)

Below is the full code and here's the key lines:

const [showAll, setShowAll] = useState(false);
const visibleHistory = showAll ? searchHistory : searchHistory.slice(0, 8);
{visibleHistory.map((entry, index) => ( ........
{searchHistory.length > 8 && ( .........

 

import React, { useState, useEffect } from 'react';
import { useCookies } from 'react-cookie';

const SidebarHistory = () => {
  const [cookies, setCookies] = useCookies(['searchHistory']);
  const [searchHistory, setSearchHistory] = useState([]);
  const [showAll, setShowAll] = useState(false);

  useEffect(() => {
    setSearchHistory(cookies.searchHistory || []);
  }, [cookies.searchHistory]);

  const handleDelete = (index) => {
    const updatedHistory = [...searchHistory];
    updatedHistory.splice(index, 1);
    setSearchHistory(updatedHistory);
    setCookies('searchHistory', updatedHistory, { path: '/' });
  };

  const visibleHistory = showAll ? searchHistory : searchHistory.slice(0, 8);

  return (
    <div className='sidebar_history'>
      <ul>
        {visibleHistory.map((entry, index) => (
          <li key={index} className='history-item'>
            {entry}
            <div className='history-overlay'>
              <a href='#'>Edit</a>
              <a href='#' onClick={() => handleDelete(index)}>Delete</a>
              <a href='#'>Share</a>
            </div>
          </li>
        ))}
      </ul>
      {searchHistory.length > 8 && (
        <div className='history-links'>
          {showAll ? (
            <a href='#' onClick={() => setShowAll(false)}>Minimize History</a>
          ) : (
            <a href='#' onClick={() => setShowAll(true)}>See All History</a>
          )}
        </div>
      )}
    </div>
  );
};

export default SidebarHistory;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...