Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading