Dash Callbacks: Adding Interactivity
You'll learn: How to write callback functions that connect user inputs to dynamic chart and content updates in Dash applications.
What Are Dash Callbacks?
A callback in Dash is like a "listener" that watches for changes. Think of it as a smart assistant: when you flip a switch (user input), it automatically updates the lights (your visualization). Callbacks are Python functions decorated with @app.callback that define what happens when users interact with your dashboard.
How Callbacks Work
Every callback has two key parts:
- Input(s): The component property you're monitoring (e.g., a dropdown's selected value)
- Output(s): The component property you'll update (e.g., a graph's figure)
When the input changes, Dash automatically runs your callback function and updates the output.
Basic Structure
from dash import Input, Output
@app.callback(
Output('my-graph', 'figure'), # What to update
Input('my-dropdown', 'value') # What to watch
)
def update_graph(selected_value):
# This function runs whenever dropdown changes
filtered_data = df[df['category'] == selected_value]
fig = px.bar(filtered_data, x='x', y='y')
return fig # Return value updates the graph
The function receives the input value as an argument, processes it (filter data, create a new chart), and returns the result. Dash handles all the reactivity automatically—no manual refresh needed!
Why This Matters
Without callbacks, your dashboard would be static. Callbacks transform passive charts into responsive, user-driven experiences where every interaction reshapes the story your data tells.
Key Takeaway: Dash callbacks connect inputs to outputs through decorated Python functions, enabling automatic, reactive updates that make dashboards truly interactive.