Let’s say you are given this design to build a simple horizontal FlatList. How can you dynamically find the width and height of the items in the flat list? We can do it in different ways but recently in my code read journey I have learned a cool trick from my colleague. First of all, let’s find the width of the item, shall we?
As we can see from the above image, the whole screen width is 376 and if we inspect our item width in Figma (which is not shown in the above image), the item width is 240. So if we take this as our general measurement we can find out the item width according to screen width.
itemWidth = screenWidth * 376/240 OR screenWidth * 0.64
Meaning that our items in the flat list are taking up 64% of the total width. So how do we define the height now? We can get the dynamic height from the width and aspect ratio.
// In Figma, our item width is 240 and height is 198
// so first we get the aspect ratio
const CARD_ASPECT_RATIO = 240 / 198; // aspectRatio = width / height
const CARD_WIDTH = Metrics.screenWidth * 0.64; // this we already found out
const CARD_HEIGHT = CARD_WIDTH / CARD_ASPECT_RATIO;
Following the same method we can find out the inner content height and width. In our case, we have a top section with empty background and bottom section with text inside it. So in order to get the top section height and width dynamically, we can use the same formula.
const IMAGE_CONTAINER_ASPECT_RATIO = 240 / 140;
const IMAGE_CONTAINER_WIDTH = CARD_WIDTH;
const IMAGE_CONTAINER_HEIGHT = IMAGE_CONTAINER_WIDTH / IMAGE_CONTAINER_ASPECT_RATIO;
Finally if we put all together it will look like this in the following snack
Thats’ it. To be honest sometimes I get a bit confused about all the dynamic measurements. But this is a good learning for me 🙂