flucas96 / st_ant_tree

A Streamlit implementation of the Ant Design Tree Component (https://ant.design/components/tree-select/).
MIT License
22 stars 1 forks source link

changing defaultValue appears only after rerun #7

Open alon-sht opened 2 months ago

alon-sht commented 2 months ago

If i set the defaultValue programatically, the changes appear in the widget only after rerun simple example:

import streamlit as st
from st_ant_tree import st_ant_tree

# random tree data
tree_data = [
    {
        "value": "parent 1",
        "title": "Parent 1",
        "children": [
            {"value": "child 1", "title": "Child 1"},
            {"value": "child 2", "title": "Child 2"},
        ],
    },
    {
        "value": "parent 2",
        "title": "Parent 2",
    },
]

preselected_opts = st.selectbox("Preselected options", [None, "Child 1", "Child 2"])
if preselected_opts:
    preselected_opts = [preselected_opts]
    preselected_opts
selected = st_ant_tree(
    tree_data,
    placeholder="Select",
    defaultValue=preselected_opts,
    key=f"selected",
)
st.write(selected)

Although preselecting "Child 1", and the optuput includes it, the widget does not show it as selected. image

flucas96 commented 2 months ago

Hm interesting the only way it worked for me was to force remounting the widget by changing the key depending on the preselected option:

import streamlit as st
from st_ant_tree import st_ant_tree

# random tree data
tree_data = [
    {
        "value": "parent 1",
        "title": "Parent 1",
        "children": [
            {"value": "child 1", "title": "Child 1"},
            {"value": "child 2", "title": "Child 2"},
        ],
    },
    {
        "value": "parent 2",
        "title": "Parent 2",
    },
]

preselected_opts = st.selectbox("Preselected options", [None, "Child 1", "Child 2"])
if preselected_opts:
    preselected_opts = [preselected_opts]
    preselected_opts

selected = st_ant_tree(
    tree_data,
    placeholder="Select",
    defaultValue=preselected_opts,
    key=f"selected_{preselected_opts}", #Change key to force remounting of the component
)
st.write(selected)

Maybe this helps in your case.