Created
June 9, 2016 19:56
-
-
Save goldhand/8ec14c6b046f73cc1bad88009c241056 to your computer and use it in GitHub Desktop.
Factory for creating React components with nth-child css selector like properties.
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
import React, {Component, PropTypes} from 'react'; | |
/** | |
* createNthChild is a factory for NthChild components. | |
* | |
* Can set conditional styling meant to simulate css's nth-child pseudo selector | |
* | |
* @param {object} [options] - styles options to pass into the icon panel | |
* @param {function} [styleFirst] - if isFirst, invoke styleLast(options.styles) | |
* @param {function} [styleLast] - if isLast, invoke styleLast(options.styles) | |
* @return {Class} - returns a react component class | |
*/ | |
function createNthChild(styles, styleFirst = s => s, styleLast = s => s) { | |
return class NthChild extends Component { | |
static propTypes = { | |
isFirst: PropTypes.bool, | |
isLast: PropTypes.bool, | |
children: PropTypes.node, | |
} | |
render() { | |
const {children, isFirst, isLast} = this.props; | |
function styleNth(nthStyles) { | |
// apply nth-child style rules to style object | |
if (isFirst) return styleFirst(nthStyles); | |
if (isLast) return styleLast(nthStyles); | |
return nthStyles; | |
} | |
const {nthStyles} = styleNth(styles); | |
return ( | |
<div style={nthStyles}> | |
{children} | |
</div> | |
); | |
} | |
}; | |
} | |
/* | |
* @example | |
* const count = 10; | |
* const panels = Array.from(Array(count).keys()).map((k, i) => { | |
* | |
* let [isFirst, isLast] = [i === 0, i === count - 1]; | |
* | |
* return ( | |
* <NthChild isFirst={isFirst} isLast={isLast} /> | |
* <div>Child Component</div> | |
* </NthChild> | |
* ); | |
* }); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment