Rick
Rick

Reputation: 381

How to traverse react tree recursively and get states of the react elements?

I use react-children-utilities to traverse react tree recursively like this:

import Children from 'react-children-utilities';
...

Children.deepForEach(window.rootNode, (child) => {
    if (child.props.key === '...') {
          //child.state === undefined
    }
});

What I need to do is accessing the state of the element, but I am not able to do so in the above code. If I understand this right: the problem is, child in the above code is a react element, not a react component. So, is there a way to get the state out of a react element?

otherwise, is there a way other than react-children-utilities to recursively traverse react tree and get states of a react component/element?

Upvotes: 4

Views: 1047

Answers (1)

fernandopasik
fernandopasik

Reputation: 10453

I'm the author of react-children-utilities. The problem you are describing I think it goes against the principles of React as the components do not expose their state to the parent components. If you need to get something from the child elements I suggest implement an event and pass a value from them.

Upvotes: 1

Related Questions