Created
September 12, 2019 12:46
-
-
Save donaldpipowitch/89a814913c8ac94d9d3b980c6a8a5f6e to your computer and use it in GitHub Desktop.
Children.map with unwrapping/flattening Fragments in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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