0

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?

nogabemist
  • 402
  • 5
  • 29

3 Answers3

0

I don't see any point in using StyleSheet in this situation, since it depends on a variable (width) that is available at the run-time, and you won't get any performance benefit with StyleSheet anymore. I would suggest to simply create a function like:

type getContainerWidth = (windowWidth: number) => number

And pass that directly to the view styles like:

<View style={[styles.sharedContainerStyle, {width: getContainerWidth(windowWidth)}]} />
Pooya Haratian
  • 765
  • 4
  • 16
0

You can create few styles:

w100: { width: '100%'}
w70: { width: '70%'}
w50: { width: '50%'}

In 'render' before 'return' (in case of class component) create 'const actualWidth' with w100/w70/w50 and pass it into 'style'.

M.N.
  • 65
  • 8
0

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({
...});
nogabemist
  • 402
  • 5
  • 29