Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inspect a component's children recursively in render method

Tags:

reactjs

I created a component called labeledElement which basically simply generates

<label {...props}>
    <span class="label">{props.label}</span>
    {props.children}
</label>

However, this is a problem if children contains multiple inputs or buttons since labels propagate clicks and focuses to children. In this scenario I would like to use a div rather than a label.

Is it possible in my render method to analyze children, see if there are more than one child matches 'button input textarea select', and depending on this output a label or a div?

I have some thoughts on how to hack it together, but all of these require wiring up to componentDidMount, inspecting the DOM and adjusting state which seems like definitely the wrong way of doing things.

like image 506
George Mauer Avatar asked Oct 05 '15 19:10

George Mauer


1 Answers

You can recursively iterate over children like this:

function visitReactElements(element, callback, depth=0) => {
  if (!element || !element.props) return;

  callback(element, depth);

  React.Children.forEach(element.props.children, (element) => {
    visitReactElements(element, callback, depth + 1);
  });
}

jsbin

You're going down a path that takes simple react and twists it into a complicated magical beast. Proceed with caution.

like image 131
Brigand Avatar answered Oct 07 '22 00:10

Brigand