Py.Cafe

kecnry/

button-state

Button example with separate hierarchical state

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
import solara

class ButtonState:
    def __init__(self, *args, **kwargs):
        self.clicks = solara.reactive(0)

    @property
    def color(self):
        color = "green"
        if self.clicks.value >= 5:
            color = "red"
        return color

    def increment(self):
        self.clicks.value += 1
        print("clicks", self.clicks)  # noqa

class State:
    def __init__(self, *args, **kwargs):
        self.buttons = solara.reactive([ButtonState(), ButtonState()])

    def add_button(self):
        self.buttons.value = self.buttons.value + [ButtonState()]


@solara.component
def Button(state):
    solara.Button(label=f"Clicked: {state.clicks}", on_click=state.increment, color=state.color)


@solara.component
def App(state):
    for button_state in state.buttons.value:
        Button(button_state)
        solara.SliderInt("clicks", value=button_state.clicks)
    solara.Button(label="New button", on_click=state.add_button)


state = State()
page = App(state=state)