sharing state between multiple components #561
|
when building dashboards I need to be able to change other components based on the change of other ones. For instance, I change a dropdown and the table below refreshed based on the new value. Is it possible to observe component state from inside another component? So far all examples I could find are with local state within the component. |
Replies: 2 comments 1 reply
|
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 |
|
I have sent you a PR to add the 2 classic React examples including yours above: #571 |

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:
Note how the shared state is declared in the
SyncedInputscom…