1

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Anushka Praveen
  • 109
  • 2
  • 13

2 Answers2

10

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 }
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Gabriel Barth
  • 116
  • 1
  • 3
  • 1
    do you know how to this useWindowsDimensions use globally? can we create a separate file to get dimensions? How does it do? I want to use useWindowsDimensions to get screen height & width in different screens. – Anushka Praveen Mar 04 '22 at 07:23
0

As advised at this article, https://spin.atomicobject.com/2021/11/12/3-ways-scale-react-native-app/

const {fontScale} = useWindowDimensions(); // import useWindowDimensions()
const styles = makeStyles(fontScale); // pass in fontScale to the StyleSheet

const makeStyles = fontScale => StyleSheet.create({
  safeAreaViewContainer: {
    minWidth: '100%',
    minHeight: '100%',
    backgroundColor: 'red',
    justifyContent: 'center',
    alignItems: 'center',
  },
... });
Hen Aharon
  • 23
  • 1
  • 7