React - delete selected loop list item

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

To handle the deletion of the selected list item when clicking the "Delete" link, you can add a function to handle the deletion and update the state accordingly. Here's an example:

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

const BuddySidebarHistory = () => {
  const [cookies, setCookies] = useCookies(['searchHistory']);
  const [searchHistory, setSearchHistory] = useState([]);

  useEffect(() => {
    // Set initial state from cookies when component mounts
    setSearchHistory(cookies.searchHistory || []);
  }, [cookies.searchHistory]);

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

  return (
    <div className='buddy_history'>
      <ul>
        {searchHistory.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>
    </div>
  );
};

export default BuddySidebarHistory;

 

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