Skip to content

Instantly share code, notes, and snippets.

@souporserious
Last active April 16, 2020 03:29
Show Gist options
  • Save souporserious/9e0a8d5a2f93a4ac08e5ec75a94a0ffa to your computer and use it in GitHub Desktop.
Save souporserious/9e0a8d5a2f93a4ac08e5ec75a94a0ffa to your computer and use it in GitHub Desktop.
Utilities to join and clone React children.
/**
* Used to clone and apply props to children
*/
function cloneChildren(children, callback) {
const childrenArray = React.Children.toArray(children).filter(
child => child !== undefined && child !== null && child !== false
)
const childrenCount = childrenArray.length
return childrenArray.map(
(child, index) =>
typeof child === 'string' ||
typeof child === 'number'
? child
: cloneElement(
child,
callback(child, {
index,
childrenCount,
firstChild: index === 0,
lastChild: index === Math.max(0, childrenCount - 1),
isEven: index % 2 === 0,
isOdd: Math.abs(index % 2) === 1,
})
)
)
}
/**
* Joins React children using a separator.
*/
function joinChildren(children, separator = ', ') {
const childrenArray = React.Children.toArray(children)
const lastChildIndex = childrenArray.length - 1
return childrenArray.reduce((result, child, index) => {
if (index < lastChildIndex) {
return result.concat([
child,
typeof separator === 'string'
? separator
: cloneElement(separator, { key: index + '-separator' }),
])
} else {
return result.concat(child)
}
}, [])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment