ProductiveRage / Bridge.React

Bindings for Bridge.NET for React - write React applications in C#!
MIT License
74 stars 14 forks source link

Support component refs #35

Closed dionrhys closed 7 years ago

dionrhys commented 7 years ago

This change makes sure the Ref property is available directly on the component props as Key is already so React will make use of that callback to expose instances of components when mounted (as is already possible for DOM elements when they mount).

This allows scenarios that aren't as simple as changing props to cause state changes. For example, allowing a parent component to trigger a Focus and Click of a child component, like so:

ParentComponent.cs

public override ReactElement Render()
{
    ActionMenu mountedActionMenu = null;

    return DOM.Div(
        null,
        DOM.Button(
            new ButtonAttributes
            {
                onClick = ev => mountedActionMenu.Trigger()
            },
            "Trigger click"
        ),
        new ActionMenu(
            model: state.ActionMenuModel,
            onChange: newModel => props.Dispatcher.Dispatch(
                new ActionMenuPageModelChanged(state.With(_ => _.ActionMenuModel, newModel))
            ),
            @ref: instance => mountedActionMenu = instance
        )
    );
}

The @ref syntax is required here because ref is a reserved keyword. It's a bit unfortunate, but I think it's ok because Refs shouldn't be overused.

React doc: https://reactjs.org/docs/refs-and-the-dom.html