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
javascript dom reactjs


source to share


No one has answered this question yet

Check out similar questions:

1835
How do I update each dependency in package.json to the latest version?
58
React renderToString () Performance and caching of responsive components
38
Getting DOM node from React child
7
React - Get ref in child component in parent component
4
How to access class name of React object in this.props.children
3
React loop through children without link
3
Using refs in react
1
link issues due to React portals and componentDidMount
1
assert react component child (ren) existence / absence using jestjs
0
React - accessing refs DOM node is "checked", how to get each checkbox value, then set the value on each of the refs nodes "checked" inside a subcomponent



All Articles
Loading...
X
Show
Funny
Dev
Pics