Py.Cafe

maartenbreddels/

solara-autofocus

Autofocus on textfield, and do not lose focus on button press

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

clicks = solara.reactive(0)
text = solara.reactive("hi there")
int_value = solara.reactive(2)

@solara.component
def Page():
    color = "green"
    if clicks.value >= 5:
        color = "red"

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

    with solara.Card("Button click will not blur the textfield"):
        solara.v.TextField(v_model=text.value, on_v_model=text.set, autofocus=True)
        # based on https://stackoverflow.com/questions/12154954/how-to-make-element-not-lose-focus-when-button-is-pressed
        # we see mousedown.prevent to not have the textfield lose focus
        solara.Button(label=f"Clicked: {clicks}", on_click=increment, color=color, click_event="mousedown.prevent")
        # this seems to lose focus sometimes
        solara.SliderInt(label='level', value=int_value)