Implementing a Tiles View in React Native (a la iOS)

How to calculate the size of the tiles to get equal spacing

@ThePracticalDev: Implementing a Tiles View in React Native (a la iOS)
{ author: @emilio_srg }

I recently had a react-native project where a certain screen had the following requirements:

This was one occasion where flex was clearly not enough, so after a lot of experimentation, I came up with the following formula:

This function, along with the right styles (which I’ll show you) provides the expected results. Look at these images:

import React , { Component } from ‘react’ ; import { Text , View , StyleSheet , Dimensions } from ‘react-native’ ; const { width } = Dimensions . get ( “window” ); export default class App extends Component { render () { const tileDimensions = calcTileDimensions ( width , 2 ) // -> change this number and see! const tiles = ‘Lorem Ipsum Dolor Sit Amet’ . split ( ‘ ‘ ) return ( < View style = { styles . container } > { tiles . map ( i => Item ({… tileDimensions , text : i }))} < /View> ); } } const Item = ({ size , margin , text }) => ( < View style = {[ styles . item , { width : size , height : size , marginHorizontal : margin }]} > < Text style = { styles . itemText } > { text } < /Text> < /View> ) const calcTileDimensions = ( deviceWidth , tpr ) => { const margin = deviceWidth / ( tpr * 10 ); const size = ( deviceWidth – margin * ( tpr * 2 )) / tpr ; return { size , margin }; }; const styles = StyleSheet . create ({ container : { justifyContent : “flex-start” , flexDirection : “row” , flexWrap : “wrap” , marginTop : 30 }, item : { backgroundColor : ‘yellow’ , alignSelf : “flex-start” , alignItems : ‘center’ , justifyContent : ‘center’ , marginBottom : 20 }, itemText : { fontSize : 20 } });

And, here it is as a Sketch in Expo. Feel free to play around with it!

Implementing a Tiles View in React Native (a la iOS)