Get expanded state of st.beta_expander

Is it possible to get the current expanded state of st.beta_expander?
For example, like this:

  expander = st.beta_expander("Expander")
  print(expander.expanded)
  with expander:
    # ...

I was looking through layouts.py which led me to delta_generator.py but couldnā€™t find anything on a possible state. Perhaps it wasnā€™t ever transferred to python and remained only in the frontend. Any help would be amazing. Thanks in advance!

1 Like

Hello @poroia , welcome to the community!

For now the expanded info is not sent back to Python. Since the team is currently working on state, we would be very interested in hearing about your usecase: what are you trying to achieve by detecting changes in the expander state?

Have a nice day,
Fanilo :balloon:

One handy thing to do would be to not run code inside the expander when itā€™s closed. Good for hiding big slow things unless wanted.

2 Likes

Thank you for your response, @andfanilo!

My use-case is mainly for more intuitive UX. I have a form in which the submit button closes the expander around the form in order to show the results, all controlled by a variable in session state. (Note that, therefore, expanded parameter is set to this variable). But since the variable is unaware of when the user interactively opens or closes the expander, if an event triggers a page re-run (like navigating between pages in a multi-page app), then the expander will use the state in the session, which may not be what the user had just opened the input to.

Also itā€™s great to hear the team is working on making streamlit stateful! Iā€™ve been using the session state hack and while it does work pretty well, itā€™s been pretty janky at times.

could the expander store its state in browser sessionStorage?

include a key to identify, maybe call it ? browser_key=ā€œsomething-for-session-storageā€

I also need this functionality.

In my use-case, I have two expanders and each has a radio list in it. I want to be able to say - if one expander is expanded (expander_state = True) then radio_selection would use the selection in this expander.

The way the expander is currently, you donā€™t have access to its current state from backend. The user clicking to expand or collapse the expander is something that happens entirely in the browser. So it would be a feature request to add this functionality.

Here is a feature request where you can vote on this:

1 Like