Inspect a recursively child component in a render method

I created a component called labeledElement , which basically just generates

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

However, this is a problem if the children contain multiple inputs or buttons, as tags spread clicks and focus on children. In this scenario, I would like to use a div instead of a label.

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

I have some thoughts on how to hack it together, but all these requirements require connecting up to componentDidMount , checking the DOM, and setting up a state that seems like a certain wrong way of doing things.

+5
source share
3 answers

You can recursively iterate over children as follows:

 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 are on a path that requires a simple reaction and turns it into a complex magical beast. Use caution.

+4
source

I created a small library to work with the React.Children framework, and you can do a deep check to see if there are one or more tags that match.

Here is the library: https://github.com/fernandopasik/react-children-utilities

You can use it as follows:

 import React from 'react'; import Children from 'react-children-utilities'; function labeledElement(props) { const hasTags = !!Children.deepFind(props.children, child => ['button', 'input', 'textarea', 'select'].includes(child.type)); const Element = hasTags ? 'div' : 'label'; return ( <Element {...props}> <span class="label">{props.label}</span> {props.children} </Element> ); } 
+1
source

I don’t know if I understand your question correctly, but I think you are looking for this

https://www.npmjs.com/package/react-if

You can than just count / check how your details and rendering of children is properly.

Hope this helps

0
source

Source: https://habr.com/ru/post/1233000/


All Articles