accordion_0.png
Cover image for joseph_appsmith

Joseph Petty Verified userVerified user

Sr. Developer Advocate

Appsmith

Building an Accordion Widget (or Expanding / Collapsible Panels, Toggles, etc)

In HTML, the details tag can be used to create a UI element that can toggle to expand and show more details, or collapse and show only the header.  Also called Accordions, these elements can be great for FAQs or other cases where you want to condense the UI. 

There's no single widget in Appsmith that can do this on its own, but we can build an Accordion by taking advantage of the container widget's auto-height feature. By toggling the visibility of other widgets in the container, we can resize the container and collapse it down to just a title. 

Building the UI

Start out with an outer container and add a text widget and a button for toggling the state. Then add an inner container widget for the content that you want to show and hide. Put any other widgets inside the inner container, like inputs or more text widgets. 

accordion

Controlling the State

Next, add a new JS Object and define a variable to control the state. This will declare the expandContainer# variables as false when the page first loads, and then we can mutate those variables to show and hide the inner containers. 

expandContainers

 

Now go back to the button at the top of the outer container set the action to JS, then use a ternary operator to toggle the value assigned with each click. 

{{JSObject1.expandContainer1 = JSObject1.expandContainer1 ? false : true}}
setup
  • The left side of the equals sign says set JSObject1.expandContainer1 to some value. 
  • The right side says if JSObject1.expandContainer1 is true, set it to false, else set it to true

You can also use the ternary operator to toggle the icon shown, so that it matches the state. 

accordion gif

Until recently, techniques like this required storing a value first, and then referencing that stored value in the widget properties. But with the new variable mutations feature, you can declare the variables in a JS Object, then update the values directly from the widget using the assignment operator. This is better for performance, but the variables do not persist with page refreshes. So the stored value approach is still useful when you want to persist the state.