Last active
April 16, 2020 03:29
-
-
Save souporserious/9e0a8d5a2f93a4ac08e5ec75a94a0ffa to your computer and use it in GitHub Desktop.
Utilities to join and clone React children.
This file contains 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
/** | |
* 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, | |
}) | |
) | |
) | |
} |
This file contains 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
/** | |
* 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