How to remove selected item from my list and move it into chips, and then when I delete the chips, it will get back to the list?

enter image description here

I made a scrollable list. Every item in the list that I select will go up into chips (the grey ones). But when I click the same item on the list again, it keeps adding to the chips. I want to remove the selected ones so no duplicated chips. (Deleting chips feature already works)

How do I do this?

import React, {useState, useEffect} from 'react'
import {Typography, Paper, Box} from '@mui/material'
import Chip from '@mui/material/Chip';
import SearchInput from '../components/SearchInput';
import DeletableChip from '../components/DeletableChip'
import { spiritualPractice } from '../constants';

const Page9 = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [selected, setSelected] = useState<string[]>([])
  const [newSpiritualPractice, setNewSpiritualPractice] = useState<string[]>([])
  const onDelete = (item) => () => {
    setSelected((value) => value.filter((v) => v !== item));

  const selectPractice = (item) =>{
    setSelected([...selected, item])

  useEffect(() => {
  }, [selected])

  const filterData = (query, data) => {
    if (!query) {
      return data;
    } else {
      return data.filter((d) => d.toLowerCase().includes(query));

  const dataFiltered = filterData(searchQuery, spiritualPractice);
  return (
            <Typography variant="h6" mt={2} sx={{ fontWeight: 'bold' }}>Passions</Typography>
            <Typography variant="body2" my={2} sx={{ fontWeight: 'normal' }}>Let everyone know what you're passionate about, by adding it to your profile.</Typography>
            <DeletableChip ></DeletableChip>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', width: 'auto'}}>
              { => (
                <Chip key={el} label={el} onDelete={onDelete(el)} sx={{m:1}}/>
            <SearchInput searchQuery={searchQuery} setSearchQuery={setSearchQuery} />
            <Paper style={{maxHeight: 200, overflowY: 'auto'}}>
              { => (
                    padding: 5,
                    justifyContent: "normal",
                    fontSize: 13,
                    margin: 1,
                    width: "250px",
                    borderWidth: "10px",
                  onClick={()=> selectPractice(d)}

export default Page9

>Solution :

You’d want to remove the selected items from dataFiltered, by checking if they are in the selected array. For example:

const dataFiltered = filterData(searchQuery, spiritualPractice)
  .filter(item => !selected.includes(item));


const filterData = (query, data) => {
  const result = query
    ? data.filter((d) => d.toLowerCase().includes(query))
    : data;
  return result.filter(item => !selected.includes(item));

Leave a Reply