Skip to content

Instantly share code, notes, and snippets.

@Saad-Bashar
Created February 5, 2021 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Saad-Bashar/26a3524e62152b871e49ba4bcf7bb4d3 to your computer and use it in GitHub Desktop.
Save Saad-Bashar/26a3524e62152b871e49ba4bcf7bb4d3 to your computer and use it in GitHub Desktop.
Dynamic height, width and aspect ratio.
import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Dimensions } from 'react-native';
import { Card } from 'react-native-paper';
const { width, height } = Dimensions.get('window');
const Metrics = {
section: 16,
halfSection: 8,
};
const CARD_WIDTH = width * 0.64;
const CARD_ASPECT_RATIO = 240 / 198;
const CARD_HEIGHT = CARD_WIDTH / CARD_ASPECT_RATIO;
const IMAGE_CONTAINER_ASPECT_RATIO = 240 / 140;
const IMAGE_CONTAINER_WIDTH = CARD_WIDTH;
const IMAGE_CONTAINER_HEIGHT =
IMAGE_CONTAINER_WIDTH / IMAGE_CONTAINER_ASPECT_RATIO;
const styles = StyleSheet.create({
topCars: {
height: CARD_HEIGHT,
width: CARD_WIDTH,
borderRadius: 12,
marginRight: Metrics.halfSection,
},
topCarsImage: {
width: IMAGE_CONTAINER_WIDTH,
height: IMAGE_CONTAINER_HEIGHT,
borderRadius: 12,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
},
});
export default function App() {
return (
<View style={{ flex: 1, paddingTop: 48 }}>
<FlatList
showsHorizontalScrollIndicator={false}
contentContainerStyle={{
paddingHorizontal: Metrics.section,
paddingBottom: Metrics.section,
}}
horizontal={true}
data={[
{
name: 'KFC',
location: 'Bukit Bintang, Kuala Lumpur',
bg: 'cyan',
},
{
name: 'MacDonalds',
location: 'Damansara, Kuala Lumpur',
bg: 'orange',
},
{
name: 'Pizza Hut',
location: 'Damansara Jaya, Kuala Lumpur',
bg: 'yellow',
},
{
name: 'Pak Punjab',
location: 'Bukit Heights, Kuala Lumpur',
bg: 'grey',
},
]}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) => {
return (
<Card style={styles.topCars}>
<View
style={[styles.topCarsImage, { backgroundColor: item.bg }]}
/>
<View style={{ padding: 12 }}>
<Text>{item.name}</Text>
<Text>{item.location}</Text>
</View>
</Card>
);
}}
/>
</View>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment