DEV Community

taiseen
taiseen

Posted on • Edited on

1

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay