Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created September 12, 2019 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpipowitch/89a814913c8ac94d9d3b980c6a8a5f6e to your computer and use it in GitHub Desktop.
Save donaldpipowitch/89a814913c8ac94d9d3b980c6a8a5f6e to your computer and use it in GitHub Desktop.
Children.map with unwrapping/flattening Fragments in React
import React, { FC, Children, ReactNode } from 'react';
import { isFragment } from 'react-is';
import styled from 'styled-components';
const SomeContainer = styled.div`
/* add some styling */
`;
const WrappedItem = styled.div`
/* add some styling */
`;
export const MyComponent: FC = ({ children }) => {
return (
<SomeContainer>
{Children.map(children, function recursive(child): ReactNode {
if (isFragment(child)) {
return Children.map(child.props.children, recursive);
} else if (child) {
return <WrappedItem>{child}</WrappedItem>;
} else {
return null;
}
})}
</SomeContainer>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment