React native follows the box-model concept of CSS. The size of the element is calculated based on the size of content, padding, border, margin. The simplest way to set the size of an element is to set width and height CSS property for an element. All dimensions in React Native is unitless and represent density-independent pixels. By setting fixed height and width, the element will look exactly the same size on different screen sizes. But there is an instance where you want to give the width and height of an element in percentage.
Directly use of percentage is not supported in React native but React native does give a dimension module which can be used to give width in percentage. Dimension module gives the width and height of the mobile device. This information can be used to set the style of an element in runtime. Below is the example of how to use Dimension module from React native:
Importing module from React Native:
import { Dimension } from ‘react-native’;
Figure out width and height of the device:
const deviceWidth = Dimension.get(“window”).width;
const deviceHeight = Dimension.get(“window”).height;
Calculate the style value:
Width: deviceWidth*<percentageValue>/100
But the simplest way is by setting width and height CSS for an element.
Leave a Reply