Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save goldhand/8ec14c6b046f73cc1bad88009c241056 to your computer and use it in GitHub Desktop.
Save goldhand/8ec14c6b046f73cc1bad88009c241056 to your computer and use it in GitHub Desktop.
Factory for creating React components with nth-child css selector like properties.
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