Toggle hide/show sidebar from Python v2

Would be nice to be able to show the sidebar from a button. For example, on mobile, opening the keyboard pushes the headers up above the viewport… effectively hiding the header links like to reopen the sidebar. So, sidebar is closed and no way to reopen.

Tried the method with Toggle hide/show sidebar from Python but after I click the button the app becomes unresponsive on mobile. Again, no more sidebar. If we cannot use the side bar on mobile maybe a dialog box where we could offer what we had put on the sidebar.

There is a persnickety detail with the sidebar (and expanders in general):

There are two different sides: what the backend (Python) think and what the frontend (browser/user) sees. The collapse/expand functionality is a “frontend-only” action; it doesn’t send information to the backend. The only thing the backend ever knows is how it was initialized. The backend does not know if the user changed the state on the front end.

So if the sidebar was last loaded in a collapsed state, then you can force it open by setting it expanded. However, if the sidebar was last loaded in an expanded state and the user has since collapsed it (themselves, or by rescaling), then telling the backend to expand it won’t do anything because it thinks that’s how it already is.

The trick is to do two page loads in succession: reload the page with the sidebar collapsed and immediately reload it again with it expanded. The will ensure the backend gets the message to override whatever state its in.

import streamlit as st
import time

if 'handler' not in st.session_state:
    st.session_state.handler = []

if len(st.session_state.handler) > 0:
    state = st.session_state.handler.pop(0)
    st.set_page_config(initial_sidebar_state=state)
    if len(st.session_state.handler) > 0:
        # A little extra wait time as without it sometimes the backend moves "too fast" for the front
        time.sleep(.1)
        st.experimental_rerun()

st.button('Open', on_click=st.session_state.handler.append, args=['expanded'])
st.button('Close', on_click=st.session_state.handler.append, args=['collapsed'])
st.button('Force Open', on_click=st.session_state.handler.extend, args=[['collapsed','expanded']])
st.button('Force Close', on_click=st.session_state.handler.extend, args=[['expanded','collapsed']])
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.