title: Passing props to specific nested children in React
body: <p>I am trying to configure some props to children.</p>
  <p>In this dummy example I am testing the function in order to specifically target any child, nested or not, with the following prop : <code>swipeMe</code>.</p>
  <p>It works very well if inside my <code>div</code> on the <code>render function</code> if it contains just a single child, like this:</p>
  <pre><code>    &lt;SwapableItems&gt;
        &lt;div&gt;
          {/*the p element will get the red color as defined on childrenHandler*/}
          &lt;p swipeMe&gt;Add Props&lt;/p&gt; 
        &lt;/div&gt;
      &lt;/SwapableItems&gt;
  </code></pre>
  <p>Yet, if I add more children into my <code>div</code>, somehow I guess that my ternary operation on <code>childrenHandler</code> is not working well and I do not know why...</p>
  <ul>
  <li>If it has children, clone this element and call <code>childrenHandler</code> passing its children.</li>
  <li>If it has my desired prop, clone de element and do something with it.</li>
  <li>If none of the above, just clone the element.</li>
  </ul>
  <pre><code>return childHasChildren
        ? React.cloneElement(child, {}, childHasChildren)
        : child.props.swipeMe
        ? React.cloneElement(child, { ...swipeMeProps })
        : React.cloneElement(child, {});
  </code></pre>
  <p>Below is the full script.
  You can also check it out on <a href="https://codesandbox.io/s/focused-sutherland-mvhqu?fontsize=14&amp;hidenavigation=1&amp;theme=dark" rel="nofollow noreferrer">Codesandbox</a></p>
  <pre><code>import React from &quot;react&quot;;
  import ReactDOM from &quot;react-dom&quot;;
  
  function App() {
    return (
      &lt;SwapableItems&gt;
        &lt;div&gt;
          &lt;p swipeMe&gt;Add Props&lt;/p&gt;
          &lt;div&gt;Don't Add Props&lt;/div&gt;
        &lt;/div&gt;
      &lt;/SwapableItems&gt;
    );
  }
  
  function SwapableItems({ children }) {
    const content = childrenHandler(children, { style: { color: &quot;red&quot; } });
    return content;
  }
  
  const childrenHandler = (children, swipeMeProps) =&gt; {
    const childEls = React.Children.toArray(children).map((child) =&gt; {
      const childHasChildren =
        child.props.children &amp;&amp; React.isValidElement(child.props.children)
          ? childrenHandler(child.props.children, swipeMeProps)
          : undefined;
      return childHasChildren
        ? React.cloneElement(child, {}, childHasChildren)
        : child.props.swipeMe
        ? React.cloneElement(child, { ...swipeMeProps })
        : React.cloneElement(child, {});
    });
    return childEls;
  };
  const rootElement = document.getElementById(&quot;root&quot;);
  ReactDOM.render(&lt;App /&gt;, rootElement);
  
  </code></pre>