Py.Cafe

kecnry/

dropdown-component

Dropdown component with user API

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import solara


class DropdownState:
    def __init__(self, label, choices):
        self._label = label
        self._choices = solara.reactive(choices)
        self._selected = solara.reactive(choices[0])

    def __repr__(self):
        return f"<{self._label} selected='{self.selected}' choices={self.choices}>"

    @property
    def choices(self):
        return self._choices.value

    @property
    def selected(self):
        return self._selected.value

    @selected.setter
    def selected(self, value):
        choices = self.choices
        if value not in choices:
            raise ValueError(f"selected must be on of {choices}")
        self._selected.value = value

@solara.component
def DropdownUI(state):
    solara.Select(state._label, values=state._choices.value, value=state._selected)


class AppState:
    def __init__(self, *args, **kwargs):
        self._dropdown = DropdownState("test-dropdown", ['choice1', 'choice2', 'choice3'])

    @property
    def dropdown(self):
        return self._dropdown

    def __repr__(self):
        return "<AppState>"


@solara.component
def App(state):
    DropdownUI(state.dropdown)


state = AppState()
page = App(state=state)

state.dropdown.selected = 'choice3'
print(state.dropdown)