0
# Components and Configuration
1
2
Custom component framework and column configuration for data editors and dataframes. These features enable extending Streamlit with custom functionality and fine-grained control over data presentation.
3
4
## Capabilities
5
6
### Custom Components
7
8
Framework for creating and integrating custom HTML/JavaScript components into Streamlit applications.
9
10
```python { .api }
11
# Available in st.components.v1 namespace
12
def html(html, *, width=None, height=None, scrolling=False):
13
"""
14
Display HTML content in an iframe with optional sizing and scrolling.
15
16
Args:
17
html (str): HTML content to display
18
width (int, optional): Component width in pixels
19
height (int, optional): Component height in pixels
20
scrolling (bool): Whether to allow scrolling within the iframe
21
22
Returns:
23
Any: Data returned from the HTML component (if any)
24
"""
25
26
def iframe(src, *, width=None, height=None, scrolling=False):
27
"""
28
Display external web page or content in an iframe.
29
30
Args:
31
src (str): URL of the content to display
32
width (int, optional): Iframe width in pixels
33
height (int, optional): Iframe height in pixels
34
scrolling (bool): Whether to allow scrolling within the iframe
35
36
Returns:
37
Any: Data returned from the iframe (if any)
38
"""
39
40
def declare_component(name, path=None, url=None):
41
"""
42
Declare a custom Streamlit component for use in the application.
43
44
Args:
45
name (str): Component name for identification
46
path (str, optional): Local path to component files
47
url (str, optional): URL where component is hosted
48
49
Returns:
50
callable: Component function that can be called to render the component
51
"""
52
```
53
54
Example usage:
55
```python
56
import streamlit.components.v1 as components
57
58
# Simple HTML component
59
html_content = """
60
<div style="background: linear-gradient(90deg, #ff6b6b, #4ecdc4);
61
color: white; padding: 20px; border-radius: 10px; text-align: center;">
62
<h2>Custom HTML Component</h2>
63
<p>This is rendered from HTML!</p>
64
<button onclick="window.parent.postMessage({type: 'click', data: 'Button clicked!'})">
65
Click Me
66
</button>
67
</div>
68
"""
69
70
# Display HTML with return value
71
result = components.html(html_content, height=150)
72
if result:
73
st.write(f"Component returned: {result}")
74
75
# Iframe component
76
components.iframe("https://example.com", height=400)
77
78
# Custom component declaration
79
# Component files in ./my_component/
80
my_component = components.declare_component("my_component", path="./my_component")
81
82
# Use custom component
83
component_value = my_component(
84
name="example",
85
value=42,
86
options=["A", "B", "C"]
87
)
88
```
89
90
### Column Configuration
91
92
Comprehensive configuration system for customizing dataframe and data editor column behavior and appearance.
93
94
```python { .api }
95
# Available in st.column_config namespace
96
97
class Column:
98
"""
99
Base column configuration with common properties.
100
101
Args:
102
label (str, optional): Column display name
103
width (str or int, optional): Column width ("small", "medium", "large", or pixels)
104
help (str, optional): Tooltip text for column header
105
disabled (bool, optional): Whether column is read-only
106
required (bool, optional): Whether column value is required
107
"""
108
109
class TextColumn(Column):
110
"""
111
Text column configuration for string data.
112
113
Args:
114
label (str, optional): Column display name
115
width (str or int, optional): Column width
116
help (str, optional): Tooltip text
117
disabled (bool, optional): Whether column is read-only
118
required (bool, optional): Whether column value is required
119
default (str, optional): Default value for new rows
120
max_chars (int, optional): Maximum number of characters allowed
121
validate (callable, optional): Validation function for input
122
"""
123
124
class NumberColumn(Column):
125
"""
126
Number column configuration for numeric data.
127
128
Args:
129
label (str, optional): Column display name
130
width (str or int, optional): Column width
131
help (str, optional): Tooltip text
132
disabled (bool, optional): Whether column is read-only
133
required (bool, optional): Whether column value is required
134
default (float, optional): Default value for new rows
135
min_value (float, optional): Minimum allowed value
136
max_value (float, optional): Maximum allowed value
137
step (float, optional): Step size for increment/decrement
138
format (str, optional): Number format string (e.g., "%.2f", "%d")
139
"""
140
141
class CheckboxColumn(Column):
142
"""
143
Checkbox column configuration for boolean data.
144
145
Args:
146
label (str, optional): Column display name
147
width (str or int, optional): Column width
148
help (str, optional): Tooltip text
149
disabled (bool, optional): Whether column is read-only
150
required (bool, optional): Whether column value is required
151
default (bool, optional): Default value for new rows
152
"""
153
154
class SelectboxColumn(Column):
155
"""
156
Selectbox column configuration for categorical data.
157
158
Args:
159
label (str, optional): Column display name
160
width (str or int, optional): Column width
161
help (str, optional): Tooltip text
162
disabled (bool, optional): Whether column is read-only
163
required (bool, optional): Whether column value is required
164
default (Any, optional): Default selected value
165
options (list): Available options to choose from
166
"""
167
168
class DatetimeColumn(Column):
169
"""
170
Datetime column configuration for timestamp data.
171
172
Args:
173
label (str, optional): Column display name
174
width (str or int, optional): Column width
175
help (str, optional): Tooltip text
176
disabled (bool, optional): Whether column is read-only
177
required (bool, optional): Whether column value is required
178
default (datetime, optional): Default datetime value
179
min_value (datetime, optional): Minimum allowed datetime
180
max_value (datetime, optional): Maximum allowed datetime
181
format (str, optional): Datetime display format
182
step (int, optional): Step size in seconds
183
"""
184
185
class DateColumn(Column):
186
"""
187
Date column configuration for date-only data.
188
189
Args:
190
label (str, optional): Column display name
191
width (str or int, optional): Column width
192
help (str, optional): Tooltip text
193
disabled (bool, optional): Whether column is read-only
194
required (bool, optional): Whether column value is required
195
default (date, optional): Default date value
196
min_value (date, optional): Minimum allowed date
197
max_value (date, optional): Maximum allowed date
198
format (str, optional): Date display format
199
"""
200
201
class TimeColumn(Column):
202
"""
203
Time column configuration for time-only data.
204
205
Args:
206
label (str, optional): Column display name
207
width (str or int, optional): Column width
208
help (str, optional): Tooltip text
209
disabled (bool, optional): Whether column is read-only
210
required (bool, optional): Whether column value is required
211
default (time, optional): Default time value
212
min_value (time, optional): Minimum allowed time
213
max_value (time, optional): Maximum allowed time
214
format (str, optional): Time display format
215
step (int, optional): Step size in seconds
216
"""
217
218
class ListColumn(Column):
219
"""
220
List column configuration for array/list data.
221
222
Args:
223
label (str, optional): Column display name
224
width (str or int, optional): Column width
225
help (str, optional): Tooltip text
226
"""
227
228
class LinkColumn(Column):
229
"""
230
Link column configuration for URL data with clickable links.
231
232
Args:
233
label (str, optional): Column display name
234
width (str or int, optional): Column width
235
help (str, optional): Tooltip text
236
disabled (bool, optional): Whether column is read-only
237
required (bool, optional): Whether column value is required
238
default (str, optional): Default URL value
239
max_chars (int, optional): Maximum URL length
240
validate (callable, optional): URL validation function
241
display_text (str or callable, optional): Text to display instead of URL
242
"""
243
244
class ImageColumn(Column):
245
"""
246
Image column configuration for displaying images from URLs.
247
248
Args:
249
label (str, optional): Column display name
250
width (str or int, optional): Column width
251
help (str, optional): Tooltip text
252
"""
253
254
class LineChartColumn(Column):
255
"""
256
Line chart column configuration for displaying small charts in cells.
257
258
Args:
259
label (str, optional): Column display name
260
width (str or int, optional): Column width
261
help (str, optional): Tooltip text
262
y_min (float, optional): Minimum Y-axis value
263
y_max (float, optional): Maximum Y-axis value
264
"""
265
266
class BarChartColumn(Column):
267
"""
268
Bar chart column configuration for displaying small bar charts in cells.
269
270
Args:
271
label (str, optional): Column display name
272
width (str or int, optional): Column width
273
help (str, optional): Tooltip text
274
y_min (float, optional): Minimum Y-axis value
275
y_max (float, optional): Maximum Y-axis value
276
"""
277
278
class ProgressColumn(Column):
279
"""
280
Progress bar column configuration for displaying progress indicators.
281
282
Args:
283
label (str, optional): Column display name
284
width (str or int, optional): Column width
285
help (str, optional): Tooltip text
286
min_value (float, optional): Minimum progress value (default 0)
287
max_value (float, optional): Maximum progress value (default 100)
288
format (str, optional): Progress display format
289
"""
290
```
291
292
Example usage:
293
```python
294
import pandas as pd
295
import streamlit as st
296
297
# Sample dataframe
298
data = pd.DataFrame({
299
"name": ["Alice", "Bob", "Charlie"],
300
"age": [25, 30, 35],
301
"active": [True, False, True],
302
"category": ["A", "B", "A"],
303
"score": [85.5, 92.1, 78.3],
304
"signup_date": ["2023-01-15", "2023-02-20", "2023-03-10"],
305
"website": ["https://alice.com", "https://bob.org", "https://charlie.net"],
306
"progress": [75, 90, 60],
307
"trend": [[1,3,2,4], [2,1,4,3], [3,4,2,1]]
308
})
309
310
# Configure columns
311
column_config = {
312
"name": st.column_config.TextColumn(
313
"Full Name",
314
help="Employee full name",
315
max_chars=50,
316
required=True
317
),
318
"age": st.column_config.NumberColumn(
319
"Age",
320
help="Employee age in years",
321
min_value=18,
322
max_value=65,
323
step=1,
324
format="%d years"
325
),
326
"active": st.column_config.CheckboxColumn(
327
"Active Status",
328
help="Whether employee is currently active",
329
default=True
330
),
331
"category": st.column_config.SelectboxColumn(
332
"Department",
333
help="Employee department",
334
options=["A", "B", "C"],
335
required=True
336
),
337
"score": st.column_config.NumberColumn(
338
"Performance Score",
339
help="Performance rating out of 100",
340
min_value=0,
341
max_value=100,
342
format="%.1f"
343
),
344
"signup_date": st.column_config.DateColumn(
345
"Start Date",
346
help="Employee start date",
347
format="YYYY-MM-DD"
348
),
349
"website": st.column_config.LinkColumn(
350
"Personal Website",
351
help="Employee personal website",
352
display_text="Visit"
353
),
354
"progress": st.column_config.ProgressColumn(
355
"Project Progress",
356
help="Current project completion percentage",
357
min_value=0,
358
max_value=100,
359
format="%d%%"
360
),
361
"trend": st.column_config.LineChartColumn(
362
"Performance Trend",
363
help="Performance over last 4 quarters"
364
)
365
}
366
367
# Display configured dataframe
368
st.data_editor(
369
data,
370
column_config=column_config,
371
use_container_width=True,
372
num_rows="dynamic" # Allow adding/removing rows
373
)
374
```
375
376
### Advanced Configuration Patterns
377
378
#### Conditional Column Configuration
379
380
```python
381
def get_column_config(user_role, data_types):
382
"""Generate column config based on user role and data."""
383
config = {}
384
385
for col_name, col_type in data_types.items():
386
base_config = {"help": f"{col_name} column"}
387
388
# Role-based permissions
389
if user_role != "admin":
390
base_config["disabled"] = col_name in ["salary", "ssn"]
391
392
# Type-specific configuration
393
if col_type == "currency":
394
config[col_name] = st.column_config.NumberColumn(
395
col_name.title(),
396
format="$%.2f",
397
min_value=0,
398
**base_config
399
)
400
elif col_type == "percentage":
401
config[col_name] = st.column_config.ProgressColumn(
402
col_name.title(),
403
min_value=0,
404
max_value=100,
405
format="%d%%",
406
**base_config
407
)
408
elif col_type == "category":
409
config[col_name] = st.column_config.SelectboxColumn(
410
col_name.title(),
411
options=get_category_options(col_name),
412
**base_config
413
)
414
415
return config
416
417
# Usage
418
user_role = get_current_user_role()
419
data_types = analyze_dataframe_types(df)
420
column_config = get_column_config(user_role, data_types)
421
422
st.data_editor(df, column_config=column_config)
423
```
424
425
#### Dynamic Image Display
426
427
```python
428
# Image column with dynamic URLs
429
image_data = pd.DataFrame({
430
"product_name": ["Widget A", "Widget B", "Widget C"],
431
"image_url": [
432
"https://example.com/images/widget-a.jpg",
433
"https://example.com/images/widget-b.jpg",
434
"https://example.com/images/widget-c.jpg"
435
],
436
"price": [19.99, 24.99, 29.99]
437
})
438
439
column_config = {
440
"product_name": st.column_config.TextColumn("Product", width="medium"),
441
"image_url": st.column_config.ImageColumn("Product Image", width="large"),
442
"price": st.column_config.NumberColumn("Price", format="$%.2f")
443
}
444
445
st.dataframe(image_data, column_config=column_config)
446
```
447
448
#### Interactive Chart Columns
449
450
```python
451
# Line chart column with time series data
452
chart_data = pd.DataFrame({
453
"stock": ["AAPL", "GOOGL", "MSFT"],
454
"current_price": [150.25, 2800.50, 300.75],
455
"price_history": [
456
[145, 148, 152, 150], # AAPL last 4 days
457
[2750, 2780, 2820, 2800], # GOOGL
458
[295, 298, 305, 301] # MSFT
459
],
460
"volatility": [0.15, 0.12, 0.18]
461
})
462
463
column_config = {
464
"stock": st.column_config.TextColumn("Symbol", width="small"),
465
"current_price": st.column_config.NumberColumn(
466
"Price",
467
format="$%.2f"
468
),
469
"price_history": st.column_config.LineChartColumn(
470
"4-Day Trend",
471
width="medium"
472
),
473
"volatility": st.column_config.ProgressColumn(
474
"Volatility",
475
min_value=0,
476
max_value=1,
477
format="%.1%%"
478
)
479
}
480
481
st.dataframe(chart_data, column_config=column_config)
482
```
483
484
### Custom Component Development
485
486
#### Basic HTML Component
487
488
```python
489
# my_component.py
490
import streamlit.components.v1 as components
491
492
def color_picker_component(default_color="#000000", key=None):
493
"""Custom color picker component."""
494
html_template = f"""
495
<div>
496
<label for="color-picker">Choose a color:</label>
497
<input type="color" id="color-picker" value="{default_color}"
498
onchange="sendColor(this.value)">
499
<div id="preview" style="width:50px;height:50px;background:{default_color};margin-top:10px;"></div>
500
</div>
501
502
<script>
503
function sendColor(color) {{
504
document.getElementById('preview').style.background = color;
505
window.parent.postMessage({{
506
type: 'streamlit:setComponentValue',
507
value: color
508
}});
509
}}
510
</script>
511
"""
512
513
return components.html(html_template, height=100, key=key)
514
515
# Usage
516
selected_color = color_picker_component(default_color="#ff6b6b", key="color")
517
if selected_color:
518
st.write(f"Selected color: {selected_color}")
519
```
520
521
#### React-based Component
522
523
```python
524
# Declare React component (assumes component built separately)
525
react_component = components.declare_component(
526
"my_react_component",
527
url="http://localhost:3001" # Development server
528
)
529
530
def data_table_component(data, editable=True, key=None):
531
"""Custom data table with advanced features."""
532
return react_component(
533
data=data.to_dict('records'),
534
columns=list(data.columns),
535
editable=editable,
536
key=key
537
)
538
539
# Usage
540
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
541
edited_data = data_table_component(df, editable=True, key="table")
542
543
if edited_data:
544
st.write("Edited data:", edited_data)
545
```
546
547
#### Component with Bidirectional Communication
548
549
```python
550
def interactive_chart_component(data, chart_type="bar", key=None):
551
"""Interactive chart that returns clicked data point."""
552
553
# Convert data to JSON for JavaScript
554
chart_data = data.to_dict('records')
555
556
html_template = f"""
557
<div id="chart-container" style="width: 100%; height: 400px;"></div>
558
559
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
560
<script>
561
const data = {chart_data};
562
const chartType = "{chart_type}";
563
564
// Create Plotly chart
565
const plotData = [{{
566
x: data.map(d => d.x),
567
y: data.map(d => d.y),
568
type: chartType,
569
marker: {{ color: 'rgb(55, 128, 191)' }}
570
}}];
571
572
const layout = {{
573
title: 'Interactive Chart',
574
xaxis: {{ title: 'X Axis' }},
575
yaxis: {{ title: 'Y Axis' }}
576
}};
577
578
Plotly.newPlot('chart-container', plotData, layout);
579
580
// Handle click events
581
document.getElementById('chart-container').on('plotly_click', function(eventData) {{
582
const point = eventData.points[0];
583
const clickedData = {{
584
x: point.x,
585
y: point.y,
586
pointIndex: point.pointIndex
587
}};
588
589
// Send data back to Streamlit
590
window.parent.postMessage({{
591
type: 'streamlit:setComponentValue',
592
value: clickedData
593
}});
594
}});
595
</script>
596
"""
597
598
return components.html(html_template, height=450, key=key)
599
600
# Usage
601
chart_data = pd.DataFrame({
602
'x': ['A', 'B', 'C', 'D'],
603
'y': [10, 15, 13, 17]
604
})
605
606
clicked_point = interactive_chart_component(chart_data, chart_type="bar", key="chart")
607
608
if clicked_point:
609
st.write(f"Clicked point: {clicked_point}")
610
st.json(clicked_point)
611
```