nth-child in React-Native

Matthew Leak
2 min readNov 2, 2016

During the development of a native iOS app that I’m currently working on, the design required for a 2 column grid layout with borders in between. Working with Style in React-Native is easy but it certainly has it’s pitfalls and many key CSS extensions that would be used without a second-thought in React Web * such as percentages, media queries and in this case, nth-child just simply don’t exist.

I took to GitHub to do some digging on using nth-child in React Native because surely I’m not the first developer to have stumbled across this requirement. Luck has it, I’m not and many developers were utilising React Native Extended Stylesheet for their nth-child needs.

However, this just didn’t sit well with me. I felt really uncomfortable with bundling another npm module with potentially tonnes of bloat into the application just to achieve nth-child. “This seems overkill?” I thought.

The problem

Adding a full border to the above Item components that are required to sit
2 by x sure enough added the dreaded double-border “effect”.

The Solution

Without wanting to include another module into the application, I wrote a really simple helper function that just checks the index of the Item component and adds/removes the side border depending on whether the index is odd or even — simple!

checkIndexIsEven (n) {
return n % 2 == 0;
}

The function then gets called on the style property and styles the component accordingly.

<View style={[styles.option, { borderRightWidth: this.checkIndexIsEven(this.props.index) ? 3 : 0}]}>
<Text>Item</Text>
</View>

Add a top border to styles.option and you get:

Voila!

* I’m calling it React Web for comparative reasons…

--

--

Matthew Leak

UK-based Technology Consultant working in London and Manchester.