Python Tutorial
Dash Layout
layout is a tree of components. html builds structure. dcc (Dash Core Components) adds graphs, dropdowns, and inputs.
html vs dcc
from dash import Dash, html, dcc
app = Dash(__name__)
app.layout = html.Div(
style={"fontFamily": "sans-serif", "padding": "1.5rem"},
children=[
html.H1("Club dashboard"),
html.Label("Choose a city"),
dcc.Dropdown(
id="city",
options=["Oslo", "Bergen", "Tromso"],
value="Oslo",
),
dcc.Graph(id="chart"),
],
)Every interactive component needs an id so callbacks can find it.
Children
Pass a list as children (or as the first positional argument of html.Div). Nest Divs to build rows and columns with CSS or Dash Bootstrap later.
📘 Real-World Deep Dive
Knowing <strong>Dash Layout (Dash)</strong> well is what turns Dash from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Dash Layout that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from dash import html
layout = html.Div([
html.H1("Dashboard"),
html.Div([
html.Label("Region"),
html.Div(id="out"),
]),
])Expected Output
(no output)Common mistakes
- Callbacks must declare
Output/Input/Statein the right order; mismatched component IDs silently produce empty updates. @app.callbackbody cannot read HTML — return only data, render in the layout.- Each request lifecycle can fire callbacks many times — debounce heavy computation with
dcc.Intervalor caching. - Treating Dash Layout as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Use
functools.lru_cacheon expensive data-loaders prefixed by their inputs. - Switch large tables to
dash_table.DataTablewithvirtualization=True. - Run in production with
gunicorn --workers 4 --threads 8and proxy through nginx. - When working with Dash, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.