React - passing ref to sibling

Viewed 13363

I need to have 2 sibling components, and 1 of them has to have a reference to another - is that possible?

I tried this:

<button ref="btn">ok</button>
<PopupComponent triggerButton={this.refs.btn} />

And even this

<button ref="btn">ok</button>
<PopupComponent getTriggerButton={() => this.refs.btn} />

But I get undefined in both situations. Any ideas?

Note: a parent component will not work for me, because I need to have multiple sets of those, like

<button />
<PopupComponent />
<button />
<PopupComponent />
<button />
<PopupComponent />

NOT like this:

<div>
  <button />
  <PopupComponent />
</div>
<div>
  <button />
  <PopupComponent />
</div>
<div>
  <button />
  <PopupComponent />
</div>
4 Answers

The following code helps me to setup communication between two siblings. The setup is done in their parent during render() and componentDidMount() calls. Hope it helps.

class App extends React.Component<IAppProps, IAppState> {
    private _navigationPanel: NavigationPanel;
    private _mapPanel: MapPanel;

    constructor() {
        super();
        this.state = {};
    }

    // `componentDidMount()` is called by ReactJS after `render()`
    componentDidMount() {
        // Pass _mapPanel to _navigationPanel
        // It will allow _navigationPanel to call _mapPanel directly
        this._navigationPanel.setMapPanel(this._mapPanel);
    }

    render() {
        return (
            <div id="appDiv" style={divStyle}>
                // `ref=` helps to get reference to a child during rendering
                <NavigationPanel ref={(child) => { this._navigationPanel = child; }} />
                <MapPanel ref={(child) => { this._mapPanel = child; }} />
            </div>
        );
    }
}
Related