Home > Software engineering >  React Native get view height
React Native get view height

Time:09-22

Green: full screen view Red: is a view style absolute bottom:0 Blue: is a view style absolute height:‘100%’

WHAT I WANT I want find the way to get height of Red View (height isn’t determined). This height I want to use it for marginBottom for Blue View.

enter image description here

CodePudding user response:

You can try onLayout method of view it will call once the rendeing of your view is completed take a look at example below

<View
      onLayout={({ nativeEvent }) => {
         const { x, y, width, height } = nativeEvent.layout
            setHeight(height)
      }}
</View>

you can have height variable defined in your state, and you can use that variable for allocating the margin bottom

You can try code below I have made changes in your expo slack

import { Text, View} from 'react-native';
import {useState} from 'react'

export default function App() {
  const [height, setHeight] = useState('')
  return (
    <View style={{
        backgroundColor: 'green',
        flex: 1
    }}>

        <View style={{
            backgroundColor: 'blue',
            position: 'absolute',
            // height: '100%',
            left: 0,
            right: 0,
            top: 0,
            bottom: height,// here is you want to have some addintional spacing try adding some value in you hight (ex. height 20)
        }}>
        </View>

        <View
            onLayout={({ nativeEvent }) => {
                const { x, y, width, height } = nativeEvent.layout
                setHeight(height)
            }}
            style={{
                backgroundColor: 'red',
                position: 'absolute',
                left: 0,
                right: 0,
                bottom: 0,
                padding: 20
            }}>
            <Text>Lorem Ipsum</Text>
        </View>

    </View>
);
}
  • Related