Home > Software design >  useWindowDimensions use in stylesheet react native
useWindowDimensions use in stylesheet react native

Time:03-04

How to use useWindowDimensions in Stylesheet. It always works only inside the function. I want to get screen height and width using useWindowDimensions inside the stylesheet in react native.

CodePudding user response:

useWindowDimensions is a hook, so we just can use it inside a functional component. Maybe there are other ways, but I'd like to suggest you something like that:

import React from 'react';
import { View, Text, StyleSheet, useWindowDimensions } from 'react-native';


const Main = () => {
   const { styles } = useStyle();
    
    return (
        <View style={styles.container}>
            <Text>Dimension Properties inside StyleSheet{'\n'}</Text>
            
            <Text>Heigth: {styles.container.height.toString()}</Text>
            <Text>Width: {styles.container.width.toString()}</Text>
        </View>

    )
}

const useStyle = () => {
    const dimensions = useWindowDimensions();
    console.log('Logging dimensions', dimensions)

    const styles = StyleSheet.create({
      container: {
        height: dimensions.height,
        width: dimensions.width,
        justifyContent: 'center',
        alignItems: 'center',
      },
    })
  
    return { styles }
}

export { Main }

Please, let me know if this helped you.

  • Related