Home App Docs Github

How do you use the same state object for multiple elements?

I am trying to create “hide” and “show” buttons for multiple elements on the same page (that work independently from one another).

After following the “state and actions” tutorial (link), all elements on the page appear and disappear when any of the buttons are pressed.

Do I need to create a different state object for each piece of content on my page? Or, is there a way to create a single state object and then limit its scope?

Hi, John! Thanks for the question.

If you are using state and actions for multiple “show and hide” buttons that affect different elements on your page, the state will need to have its own unique key for each element.

Here is an example:

Let’s say we want to be able to hide and show these two photos independently.

  1. We need to give each button an on click action (Navigate to the Element actions section located in the Data tab). For the first set of buttons, we can give the “hide” button state.imageOneHidden = true and the “show” button state.imageOneHidden = false.

  2. For the second set of buttons, we can repeat the step we did for the first set, but we need to give the state a different unique key. Lets give the “hide” button state.imageTwoHidden = true and the “show” button state.imageTwoHidden = false.

  1. Now, we can see hidden being toggled on and off separately for each set of buttons.

  1. Now, you can bind the hidden property to your content. For the top image, we will get hide from state.imageOneHidden. For image two, we will get hide from state.imageTwoHidden.

Here is the end result:

I hope this was helpful! If you have any questions let us know!

This makes sense – thanks so much!