Skip to content

sharing state between multiple components #561

Answered by rmorshea
acivitillo asked this question in Question
Discussion options

You must be logged in to vote

Yes, this is possible. The general strategy is to move state which is shared by two or more components into their nearest common parent. Here's a quick example:

from idom import component, use_state, html, run

@component
def SyncedInputs():
    value, set_value = use_state("")
    return html.p(
        Input("First input", value, set_value),
        Input("Second input", value, set_value),
    )

@component
def Input(label, value, set_value):
    def handle_change(event):
        set_value(event["target"]["value"])

    return html.label(label + " ", html.input({"value": value, "onChange": handle_change}))

run(SyncedInputs)

Note how the shared state is declared in the SyncedInputs com…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@acivitillo
Comment options

Answer selected by rmorshea
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants