Code Monkey home page Code Monkey logo

react-native-responsive-screen's Introduction

Help with maintenance would be appreciated!

If interested please send me an email: [email protected]

Contents

react-native-responsive-screen

npm version npm

react-native-responsive-screen is a small library that provides 2 simple methods so that React Native developers can code their UI elements fully responsive. No media queries needed.

It also provides an optional third method for screen orientation detection and automatic rerendering according to new dimensions.

Give it a try and make your life simpler!

Check out this medium article to see the power of the library! πŸš€

Installation

npm install react-native-responsive-screen --save

Usage

  • After the package has installed, when application loads (in real device and/or emulator), it detects the screen's width and height. I.e. for Samsung A5 2017 model it detects width: 360DP and height: 640DP (these are the values without taking into account the device's scale factor).
  • The package exposes 2 basic methods: widthPercentageToDP and heightPercentageToDP. Their names essentially mean that you can supply a "percentage like" string value to each method and it will return the DP (indipendent pixel) that correspond to the supplied percentage of current screen's width/height respectivelly. I.e. for Samsung A5 2017, if we supply to a CSS box: width: widthPercentageToDP('53%'), the rendered style will be width: 190.8 DP. Check example number 1 for how to use them.
  • Methods widthPercentageToDP and heightPercentageToDP can be used for any style (CSS) property that accepts DP as value. DP values are the ones of type number over the props mentioned in RN docs: View style props, Text style props, Image style props, Layout props and Shadow props. Use the exposed methods for all of the type number properties used in your app in order to make your app fully responsive for all screen sizes.
  • You can also provide decimal values to these 2 methods, i.e. font-size: widthPercentageToDP('3.75%').
  • The package methods can be used with or without flex depending on what you want to do and how you choose to implement it.
  • The suggested approach is to start developing from larger screens (i.e. tablets). That way you are less prone to forget adding responsive values for all properties of type number. In any case, when your screen development is done, you should test it over a big range of different screens as shown below in the How do I know it works for all devices ? section.
  • There are 2 more methods to use if you want to support responsiveness along with orientation change. These are listenOrientationChange and removeOrientationListener. To see how to use them, check example number 3.
  • You can use this package along with styled-components. To see how to do that, check example number 2.

Updates πŸš€

  • v1.4.0 onwards: The library now has flowtype support. Types should work out of the box, no additional setup needed.
  • widthPercentageToDP and heightPercentageToDP methods accept numeric values as well from version 1.2.1 onwards. That being said a width of 53% can now be written both width: widthPercentageToDP('53%') and width: widthPercentageToDP(53).

Examples

1. How to use with StyleSheet.create() and without orientation change support

import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';

class Login extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.textWrapper}>
          <Text style={styles.myText}>Login</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  textWrapper: {
    height: hp('70%'), // 70% of height device screen
    width: wp('80%')   // 80% of width device screen
  },
  myText: {
    fontSize: hp('5%') // End result looks like the provided UI mockup
  }
});

export default Login;

You can find a working example of this over the related example repository

2. How to use with StyleSheet.create() and with orientation change support

Check the README of the related example repository

3. How to use with styled components

Check the README of the related example repository

How do I know it works for all devices ?

As mentioned in "How to Develop Responsive UIs with React Native" article, this solution is already in production apps and is tested with a set of Android, iOS emulators of different screen specs, in order to verify that we always have the same end result.

Example:

The 4 blue tiles at the bottom half of the screen should take over 98% of the screen’s width in dp and 10% of the screen’s height in dp always:

Smartphones

Tablets

License

MIT

Pull

Pull requests are welcome! Please make the PR to development branch though and not master. Thanks.

react-native-responsive-screen's People

Contributors

ardavank avatar dependabot[bot] avatar esthor avatar marudy avatar mrpechi avatar robsonsky avatar sanjaypojo avatar zcarde avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-responsive-screen's Issues

Orientation Changes on imported/external StyleSheet.Create objects

I currently have an app that uses External JS/style files that exports different StyleSheet.create() objects, which will be reused across the app.
In your example of detecting orientation changes, you have put StyleSheet.create() inside the render, so it can be modified on every orientation change. However your example seems difficult to apply in my existing app code base, because I can't export objects from inside the render method. Do you have any solution for this?

Feature Request: Able to provide viewport sizes

Hey, a slight suggestion @marudy

If we could give the option, to provide the sizes that we get from our designs directly to the functions that would be better.

I have written like a code snippet, which would explain better.

import _ from 'lodash';
import {
  widthPercentageToDP,
  heightPercentageToDP
} from 'react-native-responsive-screen';

const VIEWPORT_HEIGHT = 828;
const VIEWPORT_WIDTH = 414;
export const wp = (width: number): number => {
  const widthPercentage = (width / VIEWPORT_WIDTH) * 100;
  return _.ceil(widthPercentage);
};

export const hp = (height: number): number => {
  const heightPercentage = (height / VIEWPORT_HEIGHT) * 100;
  return _.ceil(heightPercentage);
};

ERROR TypeError: Cannot read property 'setState' of undefined, js engine: hermes

Hi when i going to watch our device oriantion than showing this error :

ERROR TypeError: Cannot read property 'setState' of undefined, js engine: hermes

Here is code 🀞 :

   useEffect(() => {
    lor(); // Start listening for orientation changes
    
    return () => {
      rol(); // Stop listening when the component unmounts
    };
  }, []); 

this is screenshots:

image
image

please fix as soon as possiable

Margin Error Styled-Component

hi, for this code i get a error :
Error:Failed to parse decleration margin:13 in styled-compnent usage

const ViewCoverHeader =styled.View`
margin:${wp('2%')};
`;

update:
i added px at the end of line and fixed,
margin:${wp('2%')}px;
but this problem not happening for with and height

im using this version of styled-component
"styled-components": "^4.0.0"

Using heightPercentageToDP but with width keeping the same aspect ratio

Hey so I will have a website made for one resolution 1440x840 for laptops.

Lets say I want it to scale up and down using heightPercentageToDP but I want the width to keep the same aspect ratio as in the original site is there a way to do this? The idea being on 1920x1080 for example there would be a bit of extra space on the sides so I don't want to specify widthPercentageToDP as this can change.

Also vice versa on mobile I would scale using widthPercentageToDP without specifying height percentage as that could change to show more content on taller devices etc.

Units size expected with styled components

Hi there,

When I was using react-native-responsive-screen with styled-components, I have always getting warning messages like below:

[Sat Apr 25 2020 13:50:46.110] WARN Expected style "width: 119" to contain units
in Context.Consumer (created by StyledNativeComponent)
in StyledNativeComponent (created by Styled(Component))
in Styled(Component) (at Card/​index.js:12)
in Card (at Dashboard/​index.js:43)
in Dashboard (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:65)
in DashboardRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in BottomTabView (at createBottomTabNavigator.tsx:41)
in BottomTabNavigator (at routes.js:165)
in TabRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:212)
in AppRoutes (at App.js:27)
in App (at renderApplication.js:45)
[Sat Apr 25 2020 13:50:46.130] WARN Expected style "height: 119" to contain units
in Context.Consumer (created by StyledNativeComponent)
in StyledNativeComponent (created by Styled(Component))
in Styled(Component) (at Card/​index.js:12)
in Card (at Dashboard/​index.js:43)
in Dashboard (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:65)
in DashboardRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in BottomTabView (at createBottomTabNavigator.tsx:41)
in BottomTabNavigator (at routes.js:165)
in TabRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:212)
in AppRoutes (at App.js:27)
in App (at renderApplication.js:45)
[Sat Apr 25 2020 13:50:46.140] WARN Expected style "marginTop: 11" to contain units
in Context.Consumer (created by StyledNativeComponent)
in StyledNativeComponent (created by Styled(Component))
in Styled(Component) (at Card/​index.js:12)
in Card (at Dashboard/​index.js:43)
in Dashboard (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:65)
in DashboardRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in BottomTabView (at createBottomTabNavigator.tsx:41)
in BottomTabNavigator (at routes.js:165)
in TabRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:212)
in AppRoutes (at App.js:27)
in App (at renderApplication.js:45)
[Sat Apr 25 2020 13:50:46.150] WARN Expected style "marginBottom: 18" to contain units
in Context.Consumer (created by StyledNativeComponent)
in StyledNativeComponent (created by Styled(Component))
in Styled(Component) (at Card/​index.js:12)
in Card (at Dashboard/​index.js:43)
in Dashboard (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:65)
in DashboardRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in BottomTabView (at createBottomTabNavigator.tsx:41)
in BottomTabNavigator (at routes.js:165)
in TabRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:212)
in AppRoutes (at App.js:27)
in App (at renderApplication.js:45)
[Sat Apr 25 2020 13:50:46.170] WARN Expected style "marginRight: 11" to contain units
in Context.Consumer (created by StyledNativeComponent)
in StyledNativeComponent (created by Styled(Component))
in Styled(Component) (at Card/​index.js:12)
in Card (at Dashboard/​index.js:43)
in Dashboard (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:65)
in DashboardRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in BottomTabView (at createBottomTabNavigator.tsx:41)
in BottomTabNavigator (at routes.js:165)
in TabRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:212)
in AppRoutes (at App.js:27)
in App (at renderApplication.js:45)
[Sat Apr 25 2020 13:50:46.180] WARN Expected style "marginLeft: 11" to contain units
in Context.Consumer (created by StyledNativeComponent)
in StyledNativeComponent (created by Styled(Component))
in Styled(Component) (at Card/​index.js:12)
in Card (at Dashboard/​index.js:43)
in Dashboard (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:65)
in DashboardRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in BottomTabView (at createBottomTabNavigator.tsx:41)
in BottomTabNavigator (at routes.js:165)
in TabRoutes (at SceneView.tsx:98)
in SceneView (at useDescriptors.tsx:125)
in CardContainer (at CardStack.tsx:561)
in CardStack (at StackView.tsx:418)
in KeyboardManager (at StackView.tsx:416)
in Context.Consumer (at StackView.tsx:414)
in StackView (at createStackNavigator.tsx:82)
in StackNavigator (at routes.js:212)
in AppRoutes (at App.js:27)
in App (at renderApplication.js:45)

I'd always creating my styles like that:

`
import styled from 'styled-components/native';
import colors from '../../../themes/colors';
import {
heightPercentageToDP as hp,
widthPercentageToDP as wp
} from 'react-native-responsive-screen';

export const Wrapper = styled.View`
flex: 1;

background-color: ${colors.bgPrimary};

`;

export const Header = styled.View`
flex-direction: row;
background-color: ${colors.purple};

width: ${wp('90%')};
margin-left: auto;
margin-right: auto;
margin-top: ${hp('3%')};
margin-bottom: ${hp('2%')};

padding-top: ${hp('2%')};
padding-bottom: ${hp('2.2%')};

border-radius: ${hp('2%')};

`;

`

Cannot resolve symbol 'heightPercentageToDP'

I'm using this library on Android with no problems, everything looks great and is responsive.

However, I'm trying to get it working on iOS and running into the errors "Cannot resolve symbol 'heightPercentageToDP'" and "Cannot resolve symbol 'widthPercentageToDP'" when I try to import these functions.
Screen Shot 2021-01-15 at 2 29 30 PM

This is not just an issue with WebStorm not finding the functions, because the result when I run the app is that there is no styling -- all the margins and paddings are 0, the width of my TextInputs is the full screen, etc.

Any ideas why this isn't working for iOS? Thank you!

react-native-responsive-screen don't work in ios release version

Hello People. I have a problem with react-native-responsive-screen. When run debug IOS version, my styles are working nice, but, in production, don't work. Don't return a value. Could help me with issue? Thanks

"react-native": "0.60.5",
"react-native-responsive-screen": "^1.2.2",

Screenshots - Prod / Debug

Screen Shot 2019-10-24 at 22 39 10
Screen Shot 2019-10-24 at 22 41 03

Using the library with safe area views.

It seems that the SafeAreaView and SafeAreaProvider from react-native-safe-area-context interfers with the functionality of the library. When height total is summed to 100% bottom part of the screen is slighty cut.

What is the recommended way to go around it? Would appreciate any tips.

Font size doesn't seem to scale well when specifying as a percentage.

I'm trying to autoscale font sizes in my app, however, it's hard to find a percentage that works for all the devices. For example, I have percentages specified like this:

  xss: convertHeightPercentageToDP('1%'),
  xs: convertHeightPercentageToDP('1.75%'),
  sm: convertHeightPercentageToDP('2%'),
  md: convertHeightPercentageToDP('2.25%'),
  lg: convertHeightPercentageToDP('2.5%'),
  xl: convertHeightPercentageToDP('3%'),
  xxl: convertHeightPercentageToDP('4%')

This looks fine on an iPhone 8+, but is too big on iPhone Xs for example. What would be the best solution to make this work? Help would be appreciated. Thanks.

Not working on smaller/old devices

Hi, there thanks for this package it solved my 80% problem

Currently, I am using it for calculator keyboard layout. it worked perfectly on all the devices expect iPhone 5s,iPhone SE and iPad 2

Simulator Screen Shot - iPad 2 - 2019-04-02 at 20 18 58

Not exact at all

Hi, first of all thanks for the package.

I just downloaded it and I made a simple layout with 2 boxes, each of them 50% of the screen and then I placed an image in each of the boxes.

import React, { Component } from 'react';
import { StyleSheet, View, Image } from 'react-native';
import {
    widthPercentageToDP as wp,
    heightPercentageToDP,
    listenOrientationChange as loc,
    removeOrientationListener as rol
} from 'react-native-responsive-screen';

class Tetset extends Component {

    componentDidMount() {
        loc(this);
    }

    componentWillUnMount() {
        rol();
    }

    render() {

        const styles = StyleSheet.create({
            viewContainer: {
                flex: 1,
            },
            childContainer1: {
                backgroundColor: 'blue',
                height: heightPercentageToDP('50%')
            },
            childContainer2: {
                backgroundColor: 'red',
                height: heightPercentageToDP('50%')
            }
        });

        return (
            <View style={[styles.viewContainer]}>
                <View style={[styles.childContainer1]}>
                    <Image
                        source={require('../../img/cj.png')}
                    />
                </View>
                <View style={[styles.childContainer2]}>
                    <Image
                        source={require('../../img/cj.png')}
                    />
                </View>
            </View>
        );
    }
}

export default Tetset;

After running the app, one of the images looks more cropped from the bottom than the other, that means the boxes aren't the same size. Is there any reason for this behavior?

Here a screenshot:
screenshot_1548636099

I tested it on a physical Xiaomi Mi A1 and on a virtual Nexus 5X with the same result.
Thanks in advance.

[RN 0.58] removeOrientationListener doesn't remove the listener

Hi there, thank for you for this package.

I'm using it in the Login screen of an app I'm making, and I'm having an issue using the removeOrientationListener method. When I debug, I see that it does not remove the subscription, so when I change screens, I get the following warning:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
ExceptionsManager.js:82
    in Login (created by Context.Consumer)
    in Connect(Login) (at screens.js:43)
    in NetworkConnectivity (at ReduxNetworkProvider.js:47)
    in ReduxNetworkProvider (created by Context.Consumer)
    in Connect(ReduxNetworkProvider) (at screens.js:42)
    in Provider (at screens.js:41)
    in StoreWrapper (at ComponentWrapper.js:29)
    in WrappedComponent (at renderApplication.js:34)
    in RCTView (at View.js:45)
    in View (at AppContainer.js:98)
    in RCTView (at View.js:45)
    in View (at AppContainer.js:115)
    in AppContainer (at renderApplication.js:33)

I'm using RN 0.58.4. The issue is in EventEmitter.js:213, in the removeListener method. This requires that the original handler specified in listenOrientationChange be included in the parameters (right now, an empty function is passed instead) because of this check:

// The subscription may have been removed during this event loop.
// its listener matches the listener in method parameters
if (subscription && subscription.listener === listener) {
  subscription.remove();
}

Perhaps this was a change in recent RN version. I needed a quick fix so I patched up index.js of this library to workaround this problem, like this:

const listenOrientationChange = that => {
  //Save the handler to a property in the Component
  that.orientationChangeHandler = newDimensions => {
    // Retrieve and save new dimensions
    screenWidth = newDimensions.window.width;
    screenHeight = newDimensions.window.height;
  
    // Trigger screen's rerender with a state update of the orientation variable
    that.setState({
      orientation: screenWidth < screenHeight ? 'portrait' : 'landscape'
    });
  }
  
  Dimensions.addEventListener('change', that.orientationChangeHandler);
};

const removeOrientationListener = that => {
  //Retrieve the original handler stored in the Component
  //Requires passing (this) as a parameter to this function, too
  Dimensions.removeEventListener('change', that.orientationChangeHandler);
};

This solved the problem in my case, although a prettier solution should be possible (don't think it's okay to mess with the component properties...).

Please let me know if something isn't clear. I don't include the code of my Login page because it follows exactly this README example.

Flow type support?

We actively use the library and really like it πŸ‘ We've been trying to improve our flow coverage and were wondering if you could add flow types to the library?

Thanks!

Does not support external Stylesheets

I have been using this in my project and it has been a great help so far. One thing I have noticed though is that it does not seem to support external Stylesheets.

I figured out that width and height are not re-calculated after orientation change when you use external stylesheets, so the sizes are not accurate in one orientation, but perfectly fine for the other orientation.

I fixed this by putting the creation of the Stylesheets inside the render function as the examples suggest. While this works perfectly fine now, my code has become pretty long and messy since i have lots of styles. So I would prefer if it could work with external stylesheets.
Is this possible?

I could not come up with a better solution on my own yet but I will try as well when I have more time in the upcoming days.

Renders behind android virtual buttons.

I'm using an Android 7.1 smart phone and if I set the height to 100%, the view renders behind the virtual buttons, making it impossible to access components at the button of the view.
Please i would like to know iif I am the only person experiencing this and what I can do.
Thanks a lot in advance.

When would you use normal styling?

First off, thank you for creating this lovely package for the community. It is so simple to use and very effective for achieving responsiveness. This isn't an issue, as it is a question.

Are there any instances where you would use normal styling over heightToPercentageDP or widthToPercentageDP when trying to achieve full responsiveness?

I've been using this package for almost every attribute in react-native (fontSize, margin, padding, width , height).

Bundling failed

Hi,
I'm beginner in React Native, and I wanted to try your lib, but I get an error and I don't know how to resolve it.
Can you, please, help me?

error: bundling failed: Error: While trying to resolve module react-native-responsive-screen from file /Users/lionelcremer/WebstormProjects/first_app_demo/App.js, the package /Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/react-native-responsive-screen/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/react-native-responsive-screen/index.js. Indeed, none of these files exist:

  • /Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/react-native-responsive-screen/index.js(.native||.android.js|.native.js|.js|.android.json|.native.json|.json)
  • /Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/react-native-responsive-screen/index.js/index(.native||.android.js|.native.js|.js|.android.json|.native.json|.json)
    at ResolutionRequest.resolveDependency (/Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:92:15)
    at DependencyGraph.resolveDependency (/Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/metro/src/node-haste/DependencyGraph.js:237:485)
    at Object.resolve (/Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/metro/src/lib/transformHelpers.js:116:25)
    at dependencies.map.result (/Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/metro/src/DeltaBundler/traverseDependencies.js:298:29)
    at Array.map ()
    at resolveDependencies (/Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/metro/src/DeltaBundler/traverseDependencies.js:294:16)
    at /Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/metro/src/DeltaBundler/traverseDependencies.js:159:33
    at Generator.next ()
    at step (/Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/metro/src/DeltaBundler/traverseDependencies.js:239:307)
    at /Users/lionelcremer/WebstormProjects/first_app_demo/node_modules/metro/src/DeltaBundler/traverseDependencies.js:239:467
    BUNDLE [android, dev] ./index.js β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ 0.0% (0/1), failed.

Margin styling

Hi, thank you for creating this library. It has been very helpful in my development.

This is a question, hopefully you can help:

Can we use this for other properties, like font-size, marginTop, marginBottom, marginLeft, marginRight, borderWidth and other numeric properties? How would we use the library if we can?

Also - would we need to use flex as well? And how is flex even used properly? What's the difference between flex 1 and 68 in your article?

Thanks!

Jest encountered an unexpected token

Hi guys!

The library is amazing. Thank you ️☺️!

I am using Jest + React Native + TypeScript to write test cases for my application.

Error:

I got the following error:

Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     β€’ If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     β€’ If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     β€’ To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     β€’ If you need a custom transformation specify a "transform" option in your config.
     β€’ If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    <ROOT_DIR>/node_modules/react-native-responsive-screen/index.js:2
    import { Dimensions, PixelRatio } from 'react-native';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > | import { heightPercentageToDP } from "react-native-responsive-screen";

Environment

Here is my package.json:

"react": "17.0.2",
"react-native": "0.67.2",
"typescript": "^4.4.4"
"react-native-responsive-screen": "^1.4.2",

"@testing-library/jest-native": "^4.0.4",
"@testing-library/react-native": "^9.1.0",
"@types/jest": "^27.5.0",
"jest": "^28.1.0",
"ts-jest": "^28.0.2"

Here is my jest.config.js:

/*
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/configuration
 */

module.exports = {
  // Indicates whether the coverage information should be collected while executing the test
  collectCoverage: true,

  // The directory where Jest should output its coverage files
  coverageDirectory: 'coverage',

  // A preset that is used as a base for Jest's configuration
  preset: 'react-native',
}

Preproduce

__tests__/demo.test.tsx

import { render } from "@testing-library/react-native";
import * as React from "react";
import MyComponent from "../src/components/MyComponent";

it("test MyComponent", () => {
  const { getByTestId } = render(<MyComponent />);
});

src/components/MyComponent

import * as React from 'react';
import {Text, View} from 'react-native';
import {heightPercentageToDP} from 'react-native-responsive-screen';

const MyComponent = () => {
   return (
    <View style={{flex: heightPercentageToDP('123')}}>
      <Text>Demo</Text>
    </View>
  );
};
export default MyComponent;

Strange results in two different emulators

Hey, first of all thanks for this awesome package.

I am getting a strange result on two different emulators with the same code.

Another strange thing is when I remove flexWrap: 'wrap', property then design looks the same in both devices with no issue

Any suggestions on how to solve it?

Pixel XL Emulator
Screenshot_1590995791

Nexus 4 Emulator
Screenshot_1590995793

Here is my code:

const item = {
      backgroundColor: 'green',
      width: wp('28%'),
      height: wp('28%'),
      margin: wp('1%'),
    }`

   render(){ return (
      <Fragment>
        <View
          style={{
            backgroundColor: 'red',
            flex: 1,
            flexDirection: 'row',
            margin: wp('5%'),
            marginTop: wp('10%'),
            flexWrap: 'wrap',
          }}
        >
          <View style={item} />
          <View style={item} />
          <View style={item} />
        </View></Fragment>)
}

TypeError: (0, _scaling.responsiveHeight) is not a function.

[Mon Oct 12 2020 22:44:55.597] ERROR TypeError: (0, _scaling.responsiveHeight) is not a function. (In '(0, _scaling.responsiveHeight)(48)', '(0, _scaling.responsiveHeight)' is undefined)
[Mon Oct 12 2020 22:44:55.600] ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
[Mon Oct 12 2020 22:44:55.600] ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

this.setState this is undefined on orientation change

undefined is not an object (evaluating 'that.setState')

emit

set

D:\manal\reactnative\new\FOODISTAN\node_modules\react-native\Libraries\Components\ScrollView\ScrollView.js:808:8 emit

__callFunction
D:\manal\reactnative\new\FOODISTAN\node_modules\react-native\Libraries\ART\ReactNativeART.js:391:6

__guard
D:\manal\reactnative\new\FOODISTAN\node_modules\react-native\Libraries\ART\ReactNativeART.js:347:9
callFunctionReturnFlushedQueue

componentDidMount = () => {
    loc();
  };

  componentWillUnmount = () => {
    rol();
  };
[...]
<TouchableOpacity
                        key={i}
                        onPress={() => {
                          this.setState({ currentTab: i + 1 });
                        }}
                      >
                        <Text
           
                        >
                          text
                        </Text>
</TouchableOpacity>

Orientation listeners don't work in functional components

I was writing a functional component and I just don't know how to subscribe to the orientation changes. Since the method listenOrientationChange accepts a class instance and use the method useState from class components.

I guess that extending the listener to functional components would be great ;)

[Solved] Issue when using listenOrientationChange in hooks

Solved:

const [ state, setstate ] = React.useState(null);
React.useEffect(() => {
listenOrientationChange(setstate);
return () => {
removeOrientationListener();
};}, []);

And Package:

if (that.setState == null) {
that(screenWidth < screenHeight ? 'portrait' : 'landscape');
} else {
that.setState({
orientation: screenWidth < screenHeight ? 'portrait' : 'landscape'
});}

Hope it helps everyone

Proposed change: Dimensions API to the useWindowDimensions hook.

Hey there @marudy,
I love this package and the work that has been put into it.
I have a suggestion about moving from the Dimensions API provided by react-native to the useWindowDimensions hook newly provided by react native, as this automatically updates width and height values when screen size changes. I believe this eliminates the need for an event listener to detect when screen dimensions have changed(landscape/portrait). If you concur with this, I can raise a PR to this effect.

Feature request - is there a way to have some sort of stylesheet-based listener?

I was just thinking - is it possible to have a stylesheet based listener? Right now, it seems like you need to add the listener into each and every single component you want to resize, but I want to use this with React Native Web, and update styles upon window resize.

Having to include the styles in every component I use seems like writing a bunch of code, and couples the styles very heavily to the code in question.

Is there a better, more decoupled way to use this library?

Unable to adapt for Android device

Hi, I am very happy to use your library. When I first saw the article, I was so excited. So I can't wait to try it out in the project, but after using it, I found that I didn't get the result.The following is the code, and the sample diagram:
<Container
height={ heightPercentageToDP('81.16%') }
style={style}>

......

bdcc7190-7210-4dd3-8335-59e39ba5393d

f45c60dd-2be6-412a-a8c1-d6f3411a34ae

The same setting results in a blank gap at the bottom. So how to solve it and adapt it? I am a Chinese developer, my English is not perfect, I hope to understand, I look forward to your reply.
thanks.

Round image with wp y hp

How could I generate a round image with wp and hp, what value of borderRadius with wp ('15% ') and hp ('15%')?

TypeError: this.setState is not a function

Is this a bug report, a feature request, or a question?
Bug

Is the bug reproducible in a production environment (not a debug one)?
Yes

Environment
"react": "16.11.0",
"react-native": "0.62.2",
"react-native-responsive-screen": "^1.4.1",

Target Platform:
Android (9.0)

Bug:
TypeError: this.setState is not a function. (In 'this.setState({orientation: screenWidth < screenHeight ? 'portrait' : 'landscape'})', 'this.setState' is undefined)

I was using class component but had to change it to functional component as per project requirement. Since I changed it to functional component, orientation change is not working and am getting this error. I have attached screenshot for reference to this. Need solution for this, as i have used this library many times in my project.

WhatsApp Image 2020-07-20 at 12 00 28

Is this package still relevant?

React native has percentages that work accurately. Using this package is quite complicated and i wanted to know if it is still relevant?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.