RN Custom Style Sheet

Table of Contents

Table of Contents

Table of Contents

Table of Contents

Table of Contents

Table of Contents

Table of Contents

Table of Contents

Table of Contents

Table of Contents

Table of Contents

Brief Summary

Brief Summary

Create responsive design with the help of custom style sheet

Brief Summary

Create responsive design with the help of custom style sheet

Drop-in replacement of React Native StyleSheet with media-queries, dynamic themes, relative units, percents, math operations, scaling and other styling stuff.

Installation Instructions

Installation Instructions

First, Let assume that you have used local storage as a MMKV(Visit react-native-mmkv!) then

Installation Instructions

First, Let assume that you have used local storage as a MMKV(Visit react-native-mmkv!) then

If you want to used npm

    npm install rn-custom-style-sheet react-native-mmkv

Installation Instructions

First, Let assume that you have used local storage as a MMKV(Visit react-native-mmkv!) then

If you want to used npm

    npm install rn-custom-style-sheet react-native-mmkv

If you want to used Yarn

    yarn add rn-custom-style-sheet react-native-mmkv

Size, Units with custom matrices function

Size, Units with custom matrices function

Unit with syntax Description Example
<size><unit>@s<t[size]><sar><r> Scales size in a linear manner relative to screen size, t is threshold. Default is 0.4(Tablet) or 0.5(Phone) 5.5@s / 5.5px@s / 5.5px@st0.45
<size>@hs<sar><r> Scales size in a linear manner relative to screen width 5.5@hs / 5.5px@hs
<size><unit>@vs<sar><r> Scales size in a linear manner relative to screen height 7@vs / 7px@vs
<size><unit>@ms<factor><t[size]><sar><r> Scales size in a linear manner relative to screen size. factor is resize font. Default is 0.5, t is threshold. Default is 0.4(Tablet) or 0.5(Phone) 5@ms / 5px@ms
5@ms0.25 / 5px@ms0.25 / 5px@ms0.25t0.45
<size><unit>@mhs<factor><sar><r> Scales size in a linear manner relative to screen width. factor is resize font. Default is 0.5 5@mhs / 5px@mhs
5@mhs0.25 / 5px@mhs0.25
<size><unit>@mvs<factor><sar><r> Scales size in a linear manner relative to screen height. factor is resize font. Default is 0.5 5@mvs / 5px@mvs
5@mvs0.75 / 5px@mvs0.75
<size>@hp<r> Size percentage relative to the window height 1@hp
<size>@wp<r> Size percentage to the window width 1@wp
<size><unit>@vw<sar><r> Size relative to the window width 1.02@vw / 1.02px@vw
<size><unit>@vh<sar><r> Size relative to the window height 10@vh / 10px@vh
<size><unit>@vmin<sar><r> Size relative to the shortest dimension compared between window width and height 10@vmin / 10px@vmin
<size><unit>@vmax<sar><r> Size relative to the largest dimension compared between window width and height 10@vmax / 10px@vmax
<size><unit>@sdp<sar><r> Size relative to the window width, More detail of Visit sdp! 10@sdp / 10px@sdp
<size><unit>@ssp<sar><r> Size relative to the window width and device font size , More detail of Visit ssp! 10@ssp / 10px@ssp

Note:

- Size : Can be any positive or negative number (including decimal) for s/hs, vs, ms/mhs, mvs, sdp and ssp
- Size : Can be any positive or negative number ranging from 0 to 100 (including decimal) for vw, vh, vmin, and vmax
- Size : Can be 0 to 100 percentage (including decimal) for hp, and wp
- Unit : can be represent your size unit like, em, rem, px, cm, mm, in, pt, pc
- Factor : Can be any positive number ranging from 0 and 1 (including decimal)
- t(Threshold) : Can be any positive number ranging from 0 and 1 (including decimal)
- SAR : Can be skip aspect ratio apply to given size
- R : Can be rounding the result

Provider

  • Theme Provider
  • Forcing a device with the device prop

Provider Props

- This is a theme provider and applies to the app level js / ts.
- isSupportedOrientation : Props will be support device landscape mode because when device orientation change then change height and width. Default is false.
- isUsedBuiltInAspectRatioFunction : Default is false. Set true if you want to apply aspect ration function which are provided built-in.
- withPortraitBehaviorInLandscapeMode : Props will be support device portrait mode for scale in landscape mode because when device orientation change then change height and width (Default false).
- deviceForMediaQuery : Props will be used to apply media query device configuration at project level.
- appThemeName : Props will be used to apply default theme when you used multiple theme.
- guideLineLayout :
- width : Can be default guideline width sizes are based on standard ~5" screen mobile device or you can set based on design guideline. Default is 375
- height : Can be default guideline height sizes are based on standard ~5" screen mobile device or you can set based on design guideline. Default is 812
- aspectRatioFunction : Can be function which calculates new size based on aspect ratio condition.
- guideLineBreakpoint :
- values : The keys are your screen names, and the values are the min-width where that breakpoint should start. Default to the above values.
- unit : The unit used for the breakpoint's values. Default is px but can be changed, can be one of em, rem, cm, mm, in, pt, pc and px
- step : The increment divided by 100 used to implement exclusive breakpoints. For example, step = 5 means that down(500) will result in (max-width: 499.95px). Default is 0
- storage :
- getStorage : Can be function which get current theme mode in local storage.
- setStorage : Can be function which storage current theme mode in local storage.
- baseSizeLayout :
- thresholdOfPhone : Can be a decimal number from 0 to 1 as multiply threshold when phone device type.
- thresholdOfTablet : Can be a decimal number from 0 to 1 as multiply threshold when tablet device type.
- androidTabletRatio : Can be a decimal number for identify tablet in Android platform.
- thresholdFunction : Can be function which calculate threshold and provided baseSizeRatio & isTablet argument to manipulate data

            
              
            
          

Forcing a device with the device prop

- At times you may need to render components with different device settings than what gets automatically detected.

- This is especially useful in a Node environment where these settings can't be detected (SSR) or for testing.

Possible Keys

orientation, aspectRatio, deviceAspectRatio, pixelRatio, height, deviceHeight, width, deviceWidth, direction, prefersColorScheme and type

Possible Types

modifier can be one of: only or not
type can be one of: all, screen, tv, ios, android, windows, macos or web
aspectRatio or deviceAspectRatio : to decimal number
pixelRatio : to decimal number (device pixel density. Visit PixelRatio! )
height , width , deviceHeight , or deviceWidth : to em, rem, cm, mm, in, pt, pc and px
direction can be one of: rtl or ltr
prefersColorScheme can be one of: light ro dark

API & HOOK

01. useThemeContext

This hook provided a theme provider context. it provided a value like state, dispatch and storage.

            
              
            
          

02. useCreateHandlerSetter

This hook provided to create handle setter method.

            
              
            
          

03. useDeepCompareEffect

This hook work same as useEffect but here different is check deeply in dependence object value.

NOTE: Only use this if your values are objects or arrays that contain objects. Otherwise, you should just use React.useEffect.

            
              
            
          

04. useDeepCompareMemo

This hook work same as useMemo but here different is check deeply in dependence object value.

NOTE: Only use this if your values are objects or arrays that contain objects. Otherwise, you should just use React.useMemo.

            
              
            
          

05. useDidMount

This hook trigger when component mount. so if you need to do something when the component is mounted at that time used this hook.

            
              
            
          

06. useCurrentOrientation

If you want to get the current orientation from context but based on isSupportedOrientation props setting.

If isSupportedOrientation true than provided portrait or landscape otherwise provided portrait

            
              
            
          

07. useGuideLineBreakpoint

This hook provided a guide line break point value from theme provider context. Like values, unit and step.

            
              
            
          

08. useGuideLineLayout

This hook provided a guide line layout value from theme provider context. Like height, width and aspectRatioFunction.

            
              
            
          

09. usePortraitBehaviorInLandscapeMode

This hook provided a boolean value from theme provider context in withPortraitBehaviorInLandscapeMode key value.

            
              
            
          

10. useScreenResolution

This hook provided a screen resolution object and some internal value which are used for scaling. Like a windowWidth, windowHeight, shortDimension and longDimension.

            
              
            
          

11. useDevice

This hook provided device configuration value based on own config props or deviceForMediaQuery props from provider or default value.

            
              
            
          

12. useDeviceForMediaQuery

This hook provided device configuration value based on deviceForMediaQuery props from provider or default value.

            
              
            
          

13. useMediaQuery

This hook provided to execute from media query and based on media query provided true or false.

            
              
            
          

14. useScaleUtils

This hook provided a scale matrices utility function if you want to used in different places.

            
              
            
          

14.01 scale

Will return a linear scaled result of the provided size, based on your device's screen width & height aspect ratio

Example: scale(10)

14.02 horizontalScale

Will return a linear scaled result of the provided size, based on your device's screen width

Example: horizontalScale(10)

14.03 verticalScale

Will return a linear scaled result of the provided size, based on your device's screen height.

Example: verticalScale(10)

14.04 moderateScale

Sometimes you don't want to scale everything in a linear manner, that's where moderateScale comes in.

The cool thing about it is that you can control the resize factor (default is 0.5) and threshold.

If normal scale will increase your size by +2X, moderateScale will only increase it by +X, for example:

Example:
    scale(10) = 20;
    moderateScale(10) = 15;
    moderateScale(10, 0.1) = 11;

14.05 moderateHorizontalScale

Sometimes you don't want to scale everything in a linear manner, that's where moderateHorizontalScale comes in.

The cool thing about it is that you can control the resize factor (default is 0.5).

If normal horizontalScale will increase your size by +2X, moderateHorizontalScale will only increase it by +X, for example:

Example:
    horizontalScale(10) = 20;
    moderateHorizontalScale(10) = 15;
    moderateHorizontalScale(10, 0.1) = 11;

14.06 moderateVerticalScale

Same as moderateHorizontalScale, but using verticalScale instead of horizontalScale.

Example: moderateVerticalScale(10)

14.07 heightPercentageToDP

Their names essentially mean that you can supply a "percentage like" string value and it will return the DP (independent pixel) that correspond to the supplied percentage of current screen's height.

Example: heightPercentageToDP('50%')

14.08 widthPercentageToDP

Their names essentially mean that you can supply a "percentage like" string value and it will return the DP (independent pixel) that correspond to the supplied percentage of current screen's width.

Example: widthPercentageToDP('50%')

14.09 viewportHeight

Size relative to the window height

Example: viewportHeight(1.02)

14.10 viewportWidth

Size relative to the window width

Example: viewportWidth(10)

14.11 viewportMax

Size relative to the largest dimension compared between window width and height

Example: viewportMax(10)

14.12 viewportMin

Size relative to the shortest dimension compared between window width and height

Example: viewportMin(10)

14.13 sdp

New size unit - sdp (scalable dp). This size unit scales with the screen size. It can help developers with supporting multiple screens.

More detail of Visit sdp!

Example: sdp(10)

14.14 ssp

New size unit - ssp (scalable sp). This size unit scales with the screen size based on the sp size unit (for texts). It can help developers with supporting multiple screens.

More detail of Visit ssp!

Example: sdp(10)

15. useCurrentThemeMode

This hook provided a current theme mode, it's may be light or dark depending on user selection or system behavior.

            
              
            
          

16. useTheme

Custom hook for applying the current theme and scaling in our style object.

            
              
            
          

17. useUpdateTheme

Custom hook for update the current app theme or switch theme in our application(used for setting preference or other you have specify option in our application).

            
              
            
          

18. getScreenResolution

This method provided a screen resolution object and some internal value which are used for scaling. Like a windowWidth, windowHeight, shortDimension and longDimension.

            
              
            
          

19. listenOrientationChange

This method listen orientation change and provided a screen resolution object and some internal value which are used for scaling. Like a windowWidth, windowHeight, shortDimension and longDimension.

            
              
            
          

20. removeOrientationListener

This method remove listen orientation change event.

            
              
            
          

21. shallowEqualArrays

If you know you have two arrays in hand, and you want to know if they are shallowly equal or not, this method is for you.

            
              
            
          

22. shallowEqualObjects

If you know you have two objects in hand, and you want to know if they are shallowly equal or not, this method is for you.

            
              
            
          

23. getCurrentThemeMode

Will return current theme, based on app and system theme which are provided as a parameter.

            
              
            
          

24. AppThemeModeEnum

This enum represents app theme mode like System, Light or Dark.

            
              
          
        

25. OrientationEnum

This enum represents orientation like Portrait or Landscape.

            
              
            
          

26. ThemeModeEnum

This enum represents theme mode like Light or Dark and for System provided Light or Dark value based on system behavior.

            
              
            
          

27. UnitEnum

This enum represents size unit which is provided a package like Em(Emphemeral ), Rem(Roentgen Equivalent Man), Px(Pixel), Cm (Centimeter), Mm( Millimeter), In(Inch) , Pt(Point), Pc( Pica).

            
              
            
          

28. StorageKeys

This object represents a list of keys which can be used for storage. Like AppThemeNameKey, AppThemeModeKey and SystemThemeModeKey.

            
              
            
          

29. useGeneralScreenResolution

This hook provided a general screen resolution object and some internal value which are used for scaling. Like a baseWidth, baseHeight, isTablet, baseSizeRatio, threshold and baseSizeWithThreshold.

                    
                      
                    
                  

Breakpoint

  • What is Breakpoint
  • Default breakpoints
  • How to use breakpoints

What is Breakpoint

Breakpoints are the building blocks of responsive design.

Use them to control when your layout can be adapted at a particular viewport or device size.

Default breakpoints

Each breakpoint (a key) matches with a fixed screen width (a value):

  • base, base / extra-small: 0px
  • sm, small: 480px
  • md, medium: 768px
  • lg, large: 992px
  • xl, extra-large: 1280px
  • 2xl, double-extra-large: 1536px

How to use breakpoints in CreateStyle

key (string | number): A breakpoint key (xs, sm, etc.) or a screen width number in px or your provided breakpoint unit(guideLineBreakpointUnit props in provider).

If you want to change any of the properties values based on the breakpoint then you can do using this package same as like provided to native-base(Visit Native-Bases!)

If you provided a value in array form so at that time your given array value will be sorted by breakpoint key. For example in below example fontSize array will be sorted by breakpoint key)

Example:

fontSize: ['12@mhs', '14@mhs', '16@mhs', '18@mhs']
fontSize: { base: '12@mhs', sm: '14@mhs', md: '16@mhs', lg: '18@mhs' }

How to use breakpoints in MediaQuery

key (string | number): A breakpoint key (xs, sm, etc.) or a screen width number in px or your provided breakpoint unit(guideLineBreakpointUnit props in provider).

  • 01. upBreakpoint / up-breakpoint
  • 02. downBreakpoint / down-breakpoint
  • 03. betweenBreakpoint / between-breakpoint
  • 04. onlyBreakpoint / only-breakpoint
  • 05. notBreakpoint / not-breakpoint

01. Up (upBreakpoint / up-breakpoint)

Which matches screen widths greater than the screen size given by the breakpoint key (inclusive).

Example:

upBreakpoint: 'sm'
(up-breakpoint: sm)

02. Down (downBreakpoint / down-breakpoint)

Which matches screen widths less than the screen size given by the breakpoint key (exclusive).

Example:

downBreakpoint: 'md'
(down-breakpoint: md)

03. Between (betweenBreakpoint / between-breakpoint)

Which matches screen widths greater than the screen size given by the breakpoint key in the first argument (inclusive) and less than the screen size given by the breakpoint key in the second argument (exclusive).

Example:

betweenBreakpoint: ['sm', 'lg']
(between-breakpoint: [sm, lg])

04. Only (onlyBreakpoint / only-breakpoint)

Which matches screen widths starting from the screen size given by the breakpoint key (inclusive) and stopping at the screen size given by the next breakpoint key (exclusive).

Example:

onlyBreakpoint: 'md'
(only-breakpoint: md)

05. Not (notBreakpoint / not-breakpoint)

Which matches screen widths stopping at the screen size given by the breakpoint key (exclusive) and starting at the screen size given by the next breakpoint key (inclusive).

Example:

notBreakpoint: '2xl'
(not-breakpoint: 2xl)

MediaQuery

  • What is Media Query
  • MediaQuery Components
  • MediaQuery Components with onChange
  • Easy Mode for Media Query

What is Media Query

This package allows you to make media-query components in React Native.

This can be super useful when you want to render or remove specific elements in DOM depending on the screen size. Also, you can restructure your DOM (in terms of CSS/Sass Styling) as fit.

At times you may need to render components with different device settings than what gets automatically detected.

This is especially useful in a Node environment where these settings can't be detected (SSR) or for testing.

Possible Keys

orientation, aspectRatio, deviceAspectRatio, pixelRatio, height, deviceHeight, width, deviceWidth, direction, prefersColorScheme and type

Possible Types

modifier can be one of: only or not
type can be one of: all, screen, tv, ios, android, windows, macos or web
aspectRatio or deviceAspectRatio : to decimal number
pixelRatio : to decimal number (device pixel density. Visit PixelRatio! )
height , width , deviceHeight , or deviceWidth : to em, rem, cm, mm, in, pt, pc and px
direction can be one of: rtl or ltr
prefersColorScheme can be one of: light ro dark

MediaQuery Components

              
                
              
            

To make things more idiomatic to react, you can use camel-cased shorthands to construct media queries.

For a list of all possible shorthands and value types see Visit here!

Any numbers given as shorthand will be expanded to px (1234 will become '1234px').

The CSS media queries in the example above could be constructed like this:

              
                
              
            

MediaQuery Components with onChange

You can use the onChange callback to specify a change handler that will be called when the media query's value changes.

              
                
                
              
              
                
              
            

Easy Mode for Media Query

That's it! Now you can create your application specific breakpoints and reuse them easily. Here is an example:

              
                
                
              

And if you want a combo (the DRY way):

              
                
              
            

Create A Style

create (styles, option)

A function which returns computed styles on the basis of media queries specified, scale functionality or theming.

Here styles is plain json object to define your component or screen all styles

Arguments

CustomStyleSheet.create(_object_,_option_) : A option is contain isDark, themeName, themeMode, and isDisableScaling key properties and some other screenResolution, guideLineLayout, guideLineBreakpoint, and device key properties for internal used.

- isDark : A key represent current theme is light or dark as boolean value

- themeName : A theme name type which is currently used for current theme. For example summer, winter or monsoon.

- themeMode : A theme mode type which is currently used like light or dark

- isDisableScaling : A key to used for disabling scaling features.

Return

- A style object which is generated during application start.

Create Style Component

Create Style Component

If do you want to used style as style components then

A function which returns computed styles on the basis of scale functionality, media queries specified or theming.

Syntax : styled(Component)(({ styleOption, ...props }): CustomStyledComponentProps => ({}) )

              
                
              
            

Handle Theme Mode

  • Single
  • Multi

Handle single theme mode

If do you want to thing handle theme mode own way using Color object instead of above uses then,

1. First create colors object like below

              
                
              
            

Cont...

2. Create styles like below

              
                
              
            

Cont...

3. If you can used style component then like below

              
                
              
            

Handle multi theme mode

If do you want to thing handle theme mode own way using Color object instead of above uses then,

1. First create colors object like below

              
                
              
            

Cont...

2. Create styles like below

              
                
              
            

Cont...

3. If you can used style component then like below

              
                
              
            

Screen Shot

  • iPhone
  • Android

iPhone

iPhone 13 Portrait
iPhone 13 Portrait
iPad Air 5th Generation Portrait
iPad Air 5th Generation Portrait
iPad Pro 12.9 inch 5th Generation Portrait
iPad Pro 12.9 inch 5th Generation Portrait
iPhone 13 Landscape
iPhone 13 Landscape
iPad Air 5th Generation Landscape
iPad Air 5th Generation Landscape
iPad Pro 12.9 inch 5th Generation Landscape
iPad Pro 12.9 inch 5th Generation Landscape

Comment / Questions?

Thank you for your attention and participation

Presented: Krunal Kevadiya