|
| 1 | +import streamlit as st |
| 2 | + |
| 3 | +HTML = """ |
| 4 | + <label style='padding-right: 1em;' for='txt'>Enter text</label> |
| 5 | + <input id='txt' type='text' /> |
| 6 | +""" |
| 7 | + |
| 8 | +JS = """ |
| 9 | + export default function(component) { |
| 10 | + const { setStateValue, parentElement, data } = component; |
| 11 | +
|
| 12 | + const label = parentElement.querySelector('label'); |
| 13 | + label.innerText = data.label; |
| 14 | +
|
| 15 | + const input = parentElement.querySelector('input'); |
| 16 | + if (input.value !== data.value) { |
| 17 | + input.value = data.value ?? ''; |
| 18 | + }; |
| 19 | +
|
| 20 | + input.onkeydown = (e) => { |
| 21 | + if (e.key === 'Enter') { |
| 22 | + setStateValue('value', e.target.value); |
| 23 | + } |
| 24 | + }; |
| 25 | +
|
| 26 | + input.onblur = (e) => { |
| 27 | + setStateValue('value', e.target.value); |
| 28 | + }; |
| 29 | + } |
| 30 | +""" |
| 31 | + |
| 32 | +my_component = st.components.v2.component( |
| 33 | + "my_text_input", |
| 34 | + html=HTML, |
| 35 | + js=JS, |
| 36 | +) |
| 37 | + |
| 38 | + |
| 39 | +def my_component_wrapper( |
| 40 | + label, *, default="", key=None, on_change=lambda: None |
| 41 | +): |
| 42 | + component_state = st.session_state.get(key, {}) |
| 43 | + value = component_state.get("value", default) |
| 44 | + data = {"label": label, "value": value} |
| 45 | + result = my_component( |
| 46 | + data=data, default={"value": value}, key=key, on_value_change=on_change |
| 47 | + ) |
| 48 | + return result |
| 49 | + |
| 50 | + |
| 51 | +st.title("My custom component") |
| 52 | + |
| 53 | +if st.button("Hello World"): |
| 54 | + st.session_state["my_text_input_instance"]["value"] = "Hello World" |
| 55 | +if st.button("Clear text"): |
| 56 | + st.session_state["my_text_input_instance"]["value"] = "" |
| 57 | +result = my_component_wrapper( |
| 58 | + "Enter something", |
| 59 | + default="I love Streamlit!", |
| 60 | + key="my_text_input_instance", |
| 61 | +) |
| 62 | + |
| 63 | +st.write("Result:", result) |
| 64 | +st.write("Session state:", st.session_state) |
0 commit comments