Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse all React components including DOM components without TestUtils.findAllInRenderedTree?

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 ?

like image 689
Alexander Pustovalov Avatar asked Oct 06 '15 10:10

Alexander Pustovalov


People also ask

Can we have multiple ReactDOM render?

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.

Which method is used to add components or elements to the DOM in React?

AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .

How do I transfer data between components in React?

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.

Which method will you use in React to display components for each object in an array?

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.


1 Answers

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.

like image 184
Brigand Avatar answered Nov 05 '22 09:11

Brigand