DEV Community

taiseen
taiseen

Posted on • Updated on

Toggling inside [array] in React

When we focus on much complex logic to solve, then sometimes some simple logic is fade away from our mind... (because we pressure our brain to lode over cognitive bandwidth) & in that situation, we are just stuck at that moment...

So it's helpful to identify reusable logic of code and keep a reference somewhere else, so when needed we can easily reuse that code snippet...

So, this is simple reusable little code snippet for data toggling inside [array]...

const [inputIds, setInputIds] = useState([]);

const handleBtnToggling = (e) => {

    const id = e.target.id;

    setInputIds((pre) => !pre.includes(id) 
       ? [...pre, id] 
       : pre.filter((data) => data !== id)
    );

};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)