JSFiddle - React, Tailwind, and code Playground

by Roshan Karunarathna

React

import React, { useState } from "react";

export default function App() {
  const [fullList, setFullList] = useState([
    { id: 1, name: "List1" },
    { id: 2, name: "List2" }
  ]);
  const [favList, setFavList] = useState([]);

  const handleFavAddClick = (e) => {
 // we find the item with current id
    const findItem = fullList.find((item) => item.id === e);
    if (findItem) {
      const checkIfIsFav = favList.find((item) => item.id === e);
      // if the item is not in fav list add it, else remove it
      if (!checkIfIsFav) {
        setFavList([...favList, findItem]);
      } else {
        setFavList(favList.filter((item) => item.id !== e));
      }
    }
  };
  return (
    <div>
      Full List
      <ul>
        {fullList.map((e) => {
          const isFav = favList.find((item) => item.id === e.id);
          return (
            <div className="flex">
              <li key={e.id}>{e.name}</li>
              <button onClick={() => handleFavAddClick(e.id)}>
                {isFav ? "Unfav" : "Fav"}
              </button>
            </div>
          );
        })}
      </ul>
      Fav List
      <ul>
        {favList.map((e) => (
          <li key={e.id}>{e.name}</li>
        ))}
      </ul>
    </div>
  );
}