Skip to content

Instantly share code, notes, and snippets.

@TyrealGray
Last active August 31, 2022 14:31
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save TyrealGray/abef4f7b33351869add60ca569c7ae3c to your computer and use it in GitHub Desktop.
Save TyrealGray/abef4f7b33351869add60ca569c7ae3c to your computer and use it in GitHub Desktop.
100 Stupid Questions for React Native

100 Stupid Questions for React Native

What is React Native? Is it same as React?

React Native lets you build mobile apps using only JavaScript. It uses the same design as React, letting you compose a rich mobile UI from declarative components.

https://facebook.github.io/react-native/

Is React Native easy to learn?

It depends on what project you are going to build. As for front-end developer, you nearly need to learn nothing, only a new way to write javascript (Redux, JSX).

Do I must learn Redux?

No. (But everyone use it.)

What is JSX?

First of all, in React Native, you only need to learn javascript, you only use javascript. JSX looks like html but it is a syntax extension to javascript.

What is the benefit from JSX?

We dislike putting html tags into javascript because it creates chaos, but doesn’t document.querySelector('.login_from') this kind of code make you annoy? You have to switch tabs between project/static/html/login.html and project/src/js/login.js to check if you need something changed both in .js and .html. But now in React they are together in one component file, easy to check and does not have side effect.

https://facebook.github.io/react/docs/components-and-props.html

How to start?

Let’s build an App!

How to set a global variable?

You can use Redux or Context, but in fact I wouldn’t call it as a global variable.

How to learn Redux?

No shortcut, go through Redux document and React Native Redux examples.

What are those files under "ios/app" folder? Can I delete them?

No, those files are necessary for the app. If we want to add a third-party library that would need us to modify info.plist file. So please don’t delete anything.

Why the text does not change on the screen?

The way to do that is using setState(xxx) function or using Redux. If you want to change anything and show it on the screen, you need to make components re-render.

Why setState is causing an endless loop?

Function setState() will trigger render, and you should avoid doing this inside any render recycle function: Lifecycle in React Native Component

I need to trigger an new action after an action is done, is that possible?

Yes. If you have multi-reducer and want to use the same variables, just adding the action into both switch cases, then they will trigger in the same time. If the action you want to dispatch has side affects though then the correct way is to use Thunks and then you can dispatch an action after an action. If you are using redux thunk, you can easily combine them. It's a middleware that lets action creators return a function instead of an action.

this.props.someAction().then((responseObj: Object): void => {
      if (responseObj && responseObj.type !== THE_ACTION_YOU_DONT_WANT_TO_ACT) {
        this.props.someOtherAction();
      }
    });

Why the Redux store variables didn’t update when I trigger an action?

Variable reference problem, if you want to update an array in Redux store, using this way instead: To update an array in redux store.

Why the Simulator is extremely slow?

Please check if you accidentally press down “cmd” + “T” in iOS Simulator. If both android and iOS Simulator are extremely slow, you might need to close the debug window or set focus on the debug window.

How to debug AJAX call?

In Dev menu there is an option name Show Inspector, you could check the network in side Simulator there. If you feel the text is too small, the only choice would be some tool like Wireshark.

Why the AJAX call is fine on iOS Simulator but not working on android Simulator?

Android Simulator cannot access local host file, you need to set a Simulator host file and upload into Simulator.

Here is a video about how to do it: https://www.youtube.com/watch?v=H-GSFIr0ixs

Why the AJAX call is not working on android with POST, PUT?

Every time android Simulator(maybe only in React Native) send AJAX request, it will add "Content-Type": "charset=utf-8" to the request headers automatically. And if your server side does not accept this, it might cause error.

I see an attribute is showing on many tags that names “ref”, what is it used for?

Refs can be as string attribute or callback method: https://reactnatve.wordpress.com/2016/05/24/refs-to-components

When I close the app, the data will lost, how to keep the data?

You can use redux-persist library or write native code by yourself. So if you are using redux-persist, then you must learn how to use redux.

How to upgrade React Native version?

First of all, do not follow the wrong document. If your version is 0.37, then follow the docs of version 0.37 not the docs of the version you want to upgrade. Then, check out rn-diff to see if it is ok to skip some version directly.

For example my version 0.46.4 has to upgrade to 0.49.0 first because there is some change I have to do manually. After I make sure version 0.49.0 on my computer is working, then I upgrade to 0.52.0.

If you want to upgrade React Native version, you should know what third library you are using. Because when upgrading is done. You have to add those library one by one again.

Android Simulator is not running the newest code, and reload is not solving the problem!

Try to close the React Native packager and delete the app in your Android Simulator. Then start everything again. If the problem still there, go checking if you are using redux-persist and do the purge first.

Can I send SMS by just running code in background instead of open SMS app in iOS?

No, you have to use SMS app in iOS to send SMS text.

Can I get the user cellphone number in iOS?

No :(

How to pop up debug menu in a real device?

You can shake your cellphone if it is running in debug mode in the same wifi connection with your laptop.

Why there are always errors in Jest when I try to write some snapshots?

If the component is using WebView or something similar which is pretty complicated component, you will need to write jest.mock('WebView', () => 'WebView') to mock WebView component when you are writing snapshot.

If the component is using redux, you need to import Provider from react-redux and write the component inside of .

If the component will fetch data, you also need to mock the internet. For example you can use fetchMock.

Jest framework are changing very fast, so you might need to keep version up-to-date and check the error that isn’t causing by version itself.

Why I must write “jest.mock('WebView', () => 'WebView')” when snapshot contain a WebView?

The short explanation is snapshot will go inside of the component to make snapshot as much detail as possible, but it is not necessary and also very hard to do that with some component.

So, just mock them please :)

How to solve error “Unable to resolve module 'react/lib/ReactComponentTreeHook'”?

Make sure version in your package.json file is the version you want.

For example, "react-native: ^0.43.3" is not same as "react-native: 0.43.3".

Clean up and re-install everything.

If the error still there, then try to run

$ react-native-git-upgrade

It is painfully that use jest.mock in every snapshot, is there a way to setup once for all?

Yes, you can create a setup.js file in test folder and write the mock function there.The in the package.json file, change jest block into this:

"jest": {

"preset": "react-native",

"collectCoverage": true,

"coverageDirectory": "__coverage__",

"testRegex": "./__tests__/[^setup].*.js$",

"transformIgnorePatterns": ["node_modules/(?!react-native|native-base|react-navigation|react-native-fabric)"],

"setupFiles": ["./__tests__/setup.js"]

}

After integration react-native-push-notification, why Android devices always relaunch after clicking the notification?

added android:launchMode="singleTop" to the main activity element in AndroidManifest.xml

<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:launchMode="singleTop"
  android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
  ...
</activity>

When will componentWillUnmount be trigger?

Most of the time it will be called if this component is not on the screen. And “not on the screen” does not mean disappear, but it means the screen is not in the memory.

For example, the app has a home screen and home screen can navigate to the event screen. This means home screen will never trigger componentWillUnmount, because event screen is only cover home screen, the home screen is still there. And event screen will trigger componentWillUnmount when navigation pops the screen out.

What is the solution for “Invariant Violation: Native module cannot be null” in Jest?

Add those codes in setup.js( see the answer for "It is painfully that use jest.mock in every snapshot, is there a way to setup once for all?" ):

jest.mock('Linking', () => {

 return {

    addEventListener: jest.fn(),

    removeEventListener: jest.fn(),

    openURL: jest.fn(),

    canOpenURL: jest.fn(),

    getInitialURL: jest.fn(),

 }

})

How to mock react-native-fabric in Jest?

jest.mock('react-native-fabric', () => {

 return {

    Crashlytics: {

       crash: () => {},

    },

    Answers: {

       logCustom: () => {},

       logContentView: () => {},

    },

 }

})

How to access state inside action creator?

If there is only single action you need to trigger, normally you only need to pass the state into it.So it won’t be tricky. But if you need to trigger multi actions, you need to change :

“return dispatch =>{....}”

into

“return (dispatch, getState) => {....}”

And then you could use getState().xxxx to get reducer inside action creator, but also remember this way needs you to install redux-thunk.

Why “new Date()” get different results sometime?

When you try to debug react native, the debug is using chrome v8 engine to run javascript not native javascript core. So the results sometime are different.

Why "Date.toLocaleDateString()" ignores country settings on Android?

JSC on Android doesn't include the locale settings. It would increase the size of the APK by ~2MB. So we need to use some date format npm package by our own.

How to integrating type checking library “flow”?

1.First of all, use npm install flow-bin: npm install --save-dev flow-bin

2.Add npm script in package.json: "flow": "flow"

3.Open terminal and run: npm run flow init

4.Add //@flow on the top of the file which you want to check type. 5.After init, there should be a .flowconfig file, change it into:

[ignore]
<PROJECT_ROOT>/node_modules/.*
<PROJECT_ROOT>/flowLibs.js
[include]
[libs]
./flowLibs.js
[lints]
[options]
unsafe.enable_getters_and_setters=true

6.Create a js file “flowLibs.js” in project root, if npm run flow check cause any error like “Module_Name. Required module not found”. You should write down a code in flowLibs.js like below:

declare module 'Module_Name' { declare var exports: any; };

Why WebView on iOS looks like zoomed in?

add scalesPageToFit = {false} in WebView jsx node.

Why I already linked the library in Xcode project but still received Promise error?

Do the link manually and check if you are using Cocoapods or you have a pod file in your project. If you do, use .xworkspace to build the app not .xcodeproj. If you are not using Cocoapods and there is a pod file in your project, just delete it.

Why I run react-native-git-upgrade but nothing is changed?

When you run react-native-git-upgrade and found out your files are all not changed, first remove your project repo and reinstall again.

Then go to find react-native-git-upgrade in global npm module folder and replace git apply --3way by git apply --reject in cliEntry.js.

After you edited cliEntry.js, run react-native-git-upgrade again, and this time you will see many .rej files with conflict info inside. Resolve the conflict according to those file and remove these in the end, run yarn install again and upgrade should be done.

If you are not sure about the conflict resolution, go to here https://github.com/ncuillery/rn-diff to check the upgrade info between each version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment