Toggle Button to Close Sidebar

I have encountered the topic mentioned above and would like to modify the logic to fit a different use case. Specifically, I want the sidebar to be collapsed by default on every page reload and when I open the sidebar and click the button, I expect the sidebar to close. However, it’s not functioning correctly, I find myself having to click multiple times to close the sidebar. I have attached the reproducible code:

import streamlit as st

if "sidebar_state" not in st.session_state:
    st.session_state.sidebar_state = "collapsed"

# Streamlit set_page_config method has a 'initial_sidebar_state' argument that controls sidebar state.

# Show title and description of the app.
st.title("Example: Controlling sidebar programmatically")
    "This is an example Streamlit app to show how to collapse the sidebar programmatically."
# Toggle sidebar state to be 'collapsed'.
if st.sidebar.button("Click to collapse sidebar state"):
    st.session_state.sidebar_state = (
        "collapsed" if st.session_state.sidebar_state == "expanded" else "expanded"
    # Force an app rerun after switching the sidebar state.

You put the button in the sidebar, and to open a collapsed sidebar you use the streamlit button and not your button, so you need to press your button twice.

import streamlit as st
from streamlit import session_state as ss

if 'sidebar_state' not in ss:
    ss.sidebar_state = 'collapsed'


def change():
    ss.sidebar_state = (
        "collapsed" if ss.sidebar_state == "expanded" else "expanded"

st.sidebar.button('Click to toggle sidebar state', on_click=change)

Hi @ferdy, Thanks for the response, my use case also similar to what you said I want the user to open the sidebar using streamlit button and want to provide a button inside the sidebar to close the sidebar along with the streamlit close button (β€˜x’), I’m trying to implement some filters inside the sidebar and after clicking the apply filter button inside the sidebar I want the sidebar to be closed, also initially i want the sidebar to be collapsed is there a workaround to achieve this use case