st.sidebar in Streamlit

The sidebar is a container in Streamlit that allows us to place widgets (like sliders, text inputs, checkboxes, etc.) on the left side of the app.

It helps in:

Syntax

st.sidebar.widget_name(arguments)    

👉 It works exactly like the normal st.widget_name() functions, but places the widget inside the sidebar.

Common Widgets Used in Sidebar

Example: Simple sidebar widgets.

Python

# Importing the Streamlit library
import streamlit as st

# Sidebar title
st.sidebar.title("Sidebar Controls")

# Sidebar input widgets
name = st.sidebar.text_input("Enter your name")
age = st.sidebar.slider("Select your age", 10, 60, 25)

# Sidebar selectbox
gender = st.sidebar.selectbox("Select Gender", ["Male", "Female", "Other"])

# Display results in main area
st.write("### 👋 Hello,", name)
st.write("**Your Age:**", age)
st.write("**Gender:**", gender)    

The output of the above code is shown below:

Sidebar in Streamlit

Explanation:

Example: Sidebar for Filtering Data

Python

# Importing the Streamlit library
import streamlit as st
import pandas as pd

# Sample dataset
data = {
    "Store": ["A", "B", "C", "D"],
    "Sales": [200, 150, 300, 250],
    "Region": ["East", "West", "East", "North"]
}
df = pd.DataFrame(data)

# Sidebar filter
region = st.sidebar.selectbox("Select Region", df["Region"].unique())

# Filter data
filtered_df = df[df["Region"] == region]

# Display
st.write(f"### Stores in {region} Region")
st.dataframe(filtered_df)    

Explanation:

When to use st.sidebar

Tip: Using Sidebar Context Manager

We can also create custom sidebar sections using a cleaner syntax.

Python

with st.sidebar:
    st.header("Settings")
    theme = st.radio("Select theme:", ["Light", "Dark"])
    st.write("You selected:", theme)