Ashwin
Ashwin

Reputation: 101

Responsive Screens for React Native

How to write stylesheet in react native for apps that scale equally on all devices on both iOS and Android platform? I tried using react-native-responsive-screen packages but none of the packages did really help to scale the app properly especially when it comes to aligning contents using margins and paddings. Any suggestions on how to overcome this issue?

Upvotes: 4

Views: 4110

Answers (3)

Lanon
Lanon

Reputation: 259

First, You should understand flexbox and then make your component visible perfectly on all devices.

In this process, Some library can help you.

react-native-lightweight-responsive is so simple.

import Responsive from 'react-native-lightweight-responsive';

<View style={{
  width: Responsive.width(300),
  height: Reponsive.width(300),
}}/>

The codes above will make your components visible identically on all devices.

Upvotes: 1

Tim
Tim

Reputation: 10709

Beside the usage of the flex layout system, what I have done so far was writing a scaling function, which adapts margins and font-sizes to the different screen sizes.

Vertical Margin example:

const HEIGHT_SCALE = 667; // this is the standard iphone 7 height, but you can use a different height as your standard height. 
const scaleMargins = (margin) => {
    const ratio = margin / HEIGHT_SCALE; 
    const newScale = Math.round(ratio * SCREEN_WIDTH);
    return newScale; 
}

const MARGIN_15 = scaleMargins(15);

Usage example:

<Text style={{ marginTop: MARGIN_15, marginBottom: MARGIN_15 }}>
Your Text with adaptive margins goes here
</Text>

Adavantages

You can adapt the scaleMargins function also to have responsive font-sizes or horizontal margins/paddings. Therefore just use a different scaling factor. For a horizontal margin, you could use this scaling function:

const WIDTH_SCALE = 375; // Standard iphone 7 screen width. You can get it from Dimension.get('screen').width 
const scaleVerticalMargins = (margin) => {
    const ratio = margin / WIDTH_SCALE; 
    const newScale = Math.round(ratio * SCREEN_WIDTH);
    return newScale; 
}

Another advantage: You can create a global style class, where you calculate all your necessary margins etc. once, for the whole app.

Upvotes: 2

Muhammad Shareyar
Muhammad Shareyar

Reputation: 822

You have to use flex props in your styling that will help our view to adjust accordingly to the screen width and height.

Upvotes: 0

Related Questions