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.
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.
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