Skip to content
Advertisement

Multiple Buttons with their own Events in ReactJS

What would be the best way to handle multiple buttons that show/hide their respective DIVs.

Example of the Code I have below. As you can see it’s set to handle just the first button. I need a method to continually add more buttons that show/hide their own DIVs.

Example: When Button(A) is clicked DIV(A) fades in. If Button(A) is clicked again DIV(A) fades out. If/instead Button(B) is clicked and DIV(A) is visible, then DIV(A) fades out and DIV(B) fades in. so on.. etc..

JavaScript

Advertisement

Answer

As we want there only exists only one state that manage multiple buttons, such that no manual useState declaration, thus, we consider there is only a single state style, and it is an object, the key of style would be the button name or index, and by using changeStyle(index)() should trigger the onclick logic for button[index], for achieving the pattern like below:

JavaScript

Since we want changeStyle(index) would by default set the state style[index] to "invis".

Hence will suppose the changeStyle function will be look

JavaScript

And since we leveraged the setStyle function inside a IIFE to assign default value of each index, therefore, once we successfully set, we should design a mechanism that would stop constantly trigger it again, or else a forever render-loop will be happened.

JavaScript

And in order to improve atomicity of each setStyle operation, we should pass a callback function to the setStyle function instead of a value.

JavaScript

The handy function is done, now considering the onclick logic.

Regarding the logic of showing and hiding:

  1. apply all style to invis regardless of their current states
  2. toggle current style[index]: if it is “invis”, then set it to “vis”, vice versa.

hence, the setStyle function in onclick function should looks like:

JavaScript

Complete solution:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement