Component example: Text input
This is a text input component that demonstrates full bidirectional communication, including programmatic updates from Python.
Key concepts demonstrated
This component demonstrates the following concepts:
- Mounting a component with a key and reading component state from Session State
- Wrapping a component's raw mounting command to create a user-friendly mounting command
- Programmatic updates from Python via the
dataparameter - Syncing frontend state without interrupting user input
Complete code
For easy copying, expand the complete code below. For easier reading, the HTML and JavaScript are shown separately.
How it works
The wrapper function pattern
The wrapper function creates a reusable interface for your component:
This pattern:
- Reads the current value from Session State (falling back to
default) - Passes the value to the component via
data - Returns the result for the caller to use
Syncing without interruption
The JavaScript checks if the value has actually changed before updating:
This prevents the input from being overwritten while the user is typing. Without this check, each rerun would reset the input to the last committed value.
Programmatic updates
Buttons can modify Session State directly:
On the next rerun, the wrapper reads this new value from Session State and passes it to the component via data. The JavaScript then updates the input field.
Still have questions?
Our forums are full of helpful information and Streamlit experts.
