Component example: Simple checkbox
This is a simple checkbox that sends a state value to Python when toggled, demonstrating persistent state communication.
Key concepts demonstrated
This component demonstrates the following concepts:
- Persistent state values sent from JavaScript with
setStateValue() - Callback functions with the
on_<state>_changenaming pattern - Initializing a stateful component with the
dataanddefaultparameters - Using font from the app's theme
- Accessing state values from the component's return object
Complete code
How it works
State values vs trigger values
This example uses setStateValue() instead of setTriggerValue(). State and trigger values have the following key differences:
- State values persist across reruns. Use state values for data that represents the current state of your component.
- Trigger values reset after each rerun. Use trigger values for one-time events like button clicks.
The default parameter
The default parameter sets the initial value in Python without triggering a rerun:
To set a default value for a state value, you must also have an accompanying callback function, even if it's an empty one like lambda: None. The on_checked_change callback ensures that the "checked" attribute is available for the component and the default parameter sets its initial value in Python.
If you set a default value without an associated callback function, the mounting command will raise an error because it won't recognize the state name. Conversely, if you declare a callback function without a default value, the state will be None until the component calls setStateValue() from JavaScript.
The data parameter
The JavaScript code reads data.checked to initialize the checkbox state on the frontend:
This is a common pattern for initializing component state: default initializes the state in Python and data is used to intialize the state on the frontend. Some components might not have more than one initial state, in which case you can use the default parameter alone.
Still have questions?
Our forums are full of helpful information and Streamlit experts.
