Search code examples
react-nativeconditional-statementsscreen-sizereact-native-stylesheet

React Native - Scalable Stylesheet for Specified Screen Sizes


I need to change style sizes into 3 different sizes such as width<520, width<768, width<960

I tried to make a conditional stylesheet as

{const width = useWindowDimensions().width;
 //Codes 
 ...}

if( 0 <= width <= 520) {
const styles = StyleSheet.create({
  container: {
    width: '%100',
  },
}
else if ( 521 <= width <= 768) {
const styles = StyleSheet.create({
  container: {
    width: '%70',
  },
}
else {
const styles = StyleSheet.create({
  container: {
    width: '%50',
  },
}

How can I do such operation? is there better way?


Solution

  • I did it with this way.

        import {useWindowDimensions,...} from 'react-native';
        const [styles, setStyles] = useState(stylesS);
    
        useEffect(() => {
            if (0 <= width && width < 768) {
                // Small Screen
                setStyles(stylesS);
            } else if (768 <= width && width < 992) {
                //medium
                setStyles(stylesM);
            } else {
                //large
                setStyles(stylesL);
            }
        }, [width]);
    
    const stylesS = StyleSheet.create({
    ...});
    
    
    const stylesM = StyleSheet.create({
    ...});
    
    
    const stylesL = StyleSheet.create({
    ...});