Skip to content

Instantly share code, notes, and snippets.

@tokland
Last active January 16, 2020 10:28
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 tokland/a12511a51e1c788caf2799ceb8ec6527 to your computer and use it in GitHub Desktop.
Save tokland/a12511a51e1c788caf2799ceb8ec6527 to your computer and use it in GitHub Desktop.
Join array of React nodes with a separator
function renderJoin(nodes: ReactNode[], separator: ReactNode): ReactNode {
return nodes.flatMap((node, idx) =>
idx < nodes.length - 1 ? [node, separator] : [node]
).map((node, idx) => <React.Fragment key={idx}>{node}</React.Fragment>);
}
// Usage
const myComponent: React.FC = props => {
return <div>{renderJoin([<p>item1</p>, <p>item2</p>], <br />)}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment