Home > front end >  React Native - Scalable Stylesheet for Specified Screen Sizes
React Native - Scalable Stylesheet for Specified Screen Sizes

Time:11-28

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: '0',
  },
}
else if ( 521 <= width <= 768) {
const styles = StyleSheet.create({
  container: {
    width: 'p',
  },
}
else {
const styles = StyleSheet.create({
  container: {
    width: 'P',
  },
}

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

CodePudding user response:

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)}]} />

CodePudding user response:

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'.

  • Related