React v0.14 will no longer give an ability to traverse all rendered components inside of a root component by TestUtils.findAllInRenderedTree - DOM components will be excluded.
Is there some better practice going through all components inside of root component ?
In Vue and React, we can only render one element. Even if we have multiple elements to render, there can only be a single root element. This means if we want to render two or more elements, we have to wrap them in another element or component.
AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .
First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.
We will use the map function to access each object from the array. The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array.
You can recursively traverse nodes by iterating over the children.
function traverse(node, visitor){
return _traverse(node, visitor, {level: 0, parent: null});
}
function _traverse(node, visitor, state){
visitor(node, state);
if (!node.props) return;
var children = React.Children.toArray(node.props.children);
children.forEach((child) => _traverse(child, visitor, {
level: state.level + 1, parent: node
}));
}
Here's an example.
You could modify the function to be a map or filter instead of a forEach.
As a general rule, doing things like this is an anti-pattern aside from unit testing or metaprogramming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With