Issue
I have 2 static views: Headline and Bottom navigator (as mentioned in the attached visualization) with 3 rem and 3.5 rem height respectively, and I want to put a responsive view between them (the light blue area). The responsive view is supposed to include list views of elements (green ones) with scroll view. I have 2 questions:
How can I make the green view responsive as being between two static views? is there any way to calculate its height in a way that it would be the same on different screens?
Every green element is 7 rem in height. How can I display different amounts of (complete) elements in different screens as the maximum as possible according to the wrapper view's height? I mean that I don't want that some kind of screen will cut an element between scrolls..
I tried to give percentage height for the top and bottom views but I want their height to be static.
Solution
This is a component that I used for a recent application; feel free to modify it to suit your needs. Hopefully, this will help you find the right answer.
import React, { useState, useEffect } from "react";
import { View, Text, ScrollView, Dimensions } from "react-native";
const HeightComponent = () => {
const [wrapperHeight, setWrapperHeight] = useState(0);
const calculateGreenViewHeight = () => {
const headlineHeight = 3; // in rem
const bottomNavigatorHeight = 3.5; // in rem
const screenHeight = Dimensions.get("window").height;
const availableHeight = screenHeight - (headlineHeight + bottomNavigatorHeight) * 16; // Convert rem to pixels (16 pixels per rem)
return Math.floor(availableHeight / 7) * 7; // Adjust the height to be a multiple of 7 rem
};
const handleWrapperLayout = (event) => {
const height = event.nativeEvent.layout.height;
setWrapperHeight(height);
};
useEffect(() => {
// Calculate the initial height once the component is mounted
const initialGreenViewHeight = calculateGreenViewHeight();
// Use initialGreenViewHeight to determine the initial number of green elements to display
}, []);
return (
<View style={{ flex: 1 }} onLayout={handleWrapperLayout}>
<View
style={{
height: 3 * 16,
backgroundColor: "lightgray",
justifyContent: "center",
alignItems: "center",
}}
>
<Text>Headline</Text>
</View>
<View style={{ height: wrapperHeight, backgroundColor: "lightblue" }}>
<ScrollView>
{/* Render green elements dynamically based on the calculated height */}
{Array.from({ length: Math.floor(wrapperHeight / (7 * 16)) }).map(
(_, index) => (
<View
key={index}
style={{
height: 7 * 16,
backgroundColor: "lightgreen",
margin: 10,
}}
>
<Text>{`Element ${index + 1}`}</Text>
</View>
)
)}
</ScrollView>
</View>
<View
style={{
height: 3.5 * 16,
backgroundColor: "lightgray",
justifyContent: "center",
alignItems: "center",
}}
>
<Text>Bottom Navigator</Text>
</View>
</View>
);
};
export default HeightComponent;
Answered By - Pratik Prakash Bindage
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.