6

I am trying to map over the children of a fragment that is in turn a child of a component. For example:

const Frag = () => (
  <React.Fragment key="test-key">
    <div>test1</div>
    <div>test2</div>
  </React.Fragment>
);

const Outer = ({ children }) => (
  <div>
    {
      React.Children.map(children, (child) => (
        <a>
          {child}
        </a>
      ))
    }
  </div>
);

// Usage
<Outer>
  <Frag />
</Outer>

This will result in a single a tag even though the fragment has multiple divs inside of it. The docs (https://reactjs.org/docs/react-api.html#reactchildrenmap) seem to indicate that this should work with a keyed fragment and I think I am creating a keyed fragment correctly (https://reactjs.org/docs/fragments.html#keyed-fragments). Any help would be appreciated!

Alex Bieg
  • 355
  • 2
  • 15

1 Answers1

4

Yes, but as far as I can see - you are iterating over Outer children. Try to

React.Children.map(children[0].props.children, (child) => (

But, looking closely at your links - I see that documentation says something wrong here

the function will never be passed the container objects

Here is an example, which clearly shows that container is passed to the function:

<script src="https://unpkg.com/@babel/standalone/babel.js"></script>
<script src="https://unpkg.com/react@16.2.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.2.0/umd/react-dom.development.js"></script>
<div id="root" />
<script type="text/babel">
  const Frag = () => (
    <>
      <div>test1</div>
      <div>test2</div>
    </>
  ); 
  
  const Outer = ({ children }) => (
    <div>
      { 
        React.Children.map(children, (child) => console.log(`Child type is ${child.type.name || child.type.toString()}`) || (
        <a>
          {child}
        </a> )) 
      }
    </div>
  ); 
  
  
  ReactDOM.render((
    <div>
      <Outer>
        <>
          <div>test1</div>
          <div>test2</div>
        </>
      </Outer>
      <Outer>
        <Frag />
      </Outer>
    </div>
  ), document.getElementById('root'));
</script>
Bsalex
  • 2,847
  • 1
  • 15
  • 22
  • You're right that does work. Thanks! Just to clarify if I understood the first link correctly I shouldn't need to do this. It says that it should iterate over a keyed fragment. Do you have any insight into this? – Alex Bieg Feb 09 '18 at 22:51
  • It does render, but if you look at the resulting html both test1 and test2 are inside of a single `a` tag. I thought that given a fragment map children would return test1 and test2 inside their own `a` tags. – Alex Bieg Feb 09 '18 at 23:04