title: React: avoid rendering component's root DOM element if DOM children are empty
body: <p>I have a React component which receives <code>children</code>, wrapping them in a DOM element:</p>
  
  <pre><code>const MyComponent = ({ children }) =&gt; &lt;div&gt;{children}&lt;/div&gt;;
  </code></pre>
  
  <p>When <code>children</code> resolves to 0 DOM nodes, I want to skip rendering the container DOM element (<code>div</code> in this example).</p>
  
  <p>(This is because the container DOM element may contribute semantics or styles which we don't want/need if the element is going to be empty.)</p>
  
  <p>E.g.</p>
  
  <pre><code>const MySubComponent = () =&gt; null;
  
  declare const maybeChild: string | undefined;
  const el = &lt;MySubComponent /&gt;;
  
  const el = (
    &lt;MyComponent&gt;
      {maybeChild}
      {el}
    &lt;/MyComponent&gt;
  )
  </code></pre>
  
  <p>In this example, the resulting DOM would be <code>&lt;div&gt;&lt;/div&gt;</code>.</p>
  
  <p>Presumably I should do this by counting the number of <em>DOM</em> children inside <code>MyComponent</code> (using this as a condition for what to render), but there doesn't seem to be an easy way to do this. (The <a href="https://reactjs.org/docs/react-api.html#reactchildren" rel="nofollow noreferrer"><code>React.Children</code> API</a> refers to the children in the React node tree, rather than the DOM, so this doesn't seem to be helpful in this case.)</p>
  
  <p>One solution I'm aware of is to ensure a 1:1 mapping of React nodes to DOM nodes. However this seems to be impractical because components often have rendering conditions inside of them.</p>