Py.Cafe

johnarban/

Learning Solara Reactives and Rendering

A simple project to try to understand how reactives and rendering interact

DocsPricing
  • app.py
  • data.py
  • render_logger.py
  • requirements.txt
  • style.css
  • utils.py
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
56
57
58
59
60
61
62
63

from pathlib import Path
import solara
from solara.toestand import Reactive, Ref
from utils import plus
from render_logger import RenderLogger, RenderDisplay

# reactive variables will trigger a component rerender
# when changed.
# When you change the default (now 0), hit the embedded browser
# refresh button to reset the state
global_clicks = solara.reactive(0)


@solara.component
def Counter(value: Reactive | int):
    RenderLogger('Counter')
    counter = solara.use_reactive(value)

    with solara.Row(justify='space-evenly'):
        solara.Info(f"Local Counter {counter.value}")
        solara.Button(f"Local Counter+: {counter}", on_click=plus(counter))

@solara.component
def SimpleCounter(value: int):
    RenderLogger('SimpleCounter')
    solara.Info(f"SimpleCounter: {value}")


@solara.component
def Page():
    RenderLogger('Page')
    RenderDisplay()
    
    solara.lab.theme.dark = True
    solara.Style(Path('style.css'))

    clicks = solara.use_reactive(0)

    solara.Text(f"Global Clicks: {global_clicks.value}")
    solara.Text(f"Local Clicks: {clicks.value}")
    
    

    with solara.Card("Counter"):
        solara.Markdown("""
            The local `clicks` reactive is passed to 
            Counter and used there via `use_reactive`
            """)
        Counter(clicks)
    
    with solara.Card("SimpleCounter"):
        SimpleCounter(clicks.value)
    


    with solara.Column(align='start'):
        with solara.Row():
            solara.Button(f"Clicked: {clicks.value}", on_click=plus(clicks))
            solara.Button(f"Global Clicked: {global_clicks}", on_click=plus(global_clicks))

    
    solara.Row()