React - How can I give each child component a unique ref?

I have a parent component that displays one of several child components:

class Parent extends React.Component {
  ...
  render() {
    const activeChild = this.state.activeChild; // 0, 1, 2, etc.
    return (
      <div>
        {this.props.children[activeChild]}
      </div>
    );
  }
}

      

Each of these child components must have ref

a unique DOM node for their own. In my case, I need to pass each child node to a third party library in order to draw something on it (for example: render, canvas or map).

The problem is that when child components appear at the same "point" in the React tree, they all share the same at different times ref

. (I think)

Here's a JSFiddle demonstrating the problem using Leaflet.js.

When all children are rendered separately, they each get their own DOM node to draw their map. But when they are shown once, only the first one can draw on the ref

'd DOM node.

Can I tell React to use (and display) separate nodes for each individual child ref

, even if the children are mounted at a single point?

If not, is there a better approach to this problem?

+3


source to share





All Articles