Search code examples
reactjsmaterial-uitsx

React in tsx delete state value onClick


I want to filter categories and need to see them if i click on the category. I also need to remove them if i click on them again. I saved all my active categories in a state and want to delete them after i click on them again, now is my question how do i do that the smartest way? State:

const [activeCategories, setActiveCategories] = useState<string[]>([]);

function handleClick(catId: string) {
    setActiveCategories([...activeCategories, catId]);
}

With ActiveCategories ill get the active Id's.


Solution

  • Modify the handleClick function to check if catId exists. Remove it if it does and add it if it doesn't exist in state:

    function handleClick(catId: string) {
        if(activeCategories.findIndex(id => catId === id) >= 0){
            const updateState = activeCategories.filter(id => id !== catId)
            setActiveCategories(updateState);
        } else {
            setActiveCategories([...activeCategories, catId]);
        }
    }