C
C
copal2016-03-30 21:00:45
React
copal, 2016-03-30 21:00:45

How to defeat ReactDOM.findDOMNode(child) in React.Children.forEach?

I can’t solve this problem for two hours, because there are examples in Google, but for some reason they don’t work for me.
ReactDOM.findDOMNode(child) in React.Children.forEach says that child must be a component instance... Here is an example https://jsbin.com/suhutulili/edit?js ,console

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2016-03-30
@copal

No no no, there is not much logic here. children are components not installed in the node's DOM. You can do something like this https://jsbin.com/casomojovo/edit?js,console . And already through refs you can pull out DOMNode

class Container extends React.Component {
   constructor(props){
     super(props);
   }
   
   componentDidMount(){
     console.log('componentDidMount', Object.keys(this.refs));
     // outputs: [ 'ch0', 'ch1' ]
   }
   
   render(){
     
     return (
       <div>{React.Children.map(this.props.children, (ch, i) => React.cloneElement(ch, { ref: 'ch' + i }))}</div>
     );
   }
}

ReactDOM.render(
  <Container>
    <div>hello</div>
    <div>world</div>
  </Container>, 
  document.querySelector('.main-container')
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question