paint-brush
The FAQs of React Nativeby@Kiran
401 reads
401 reads

The FAQs of React Native

by KiranOctober 2nd, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

React Native is a framework created by Facebook that is used for building native apps using React. It is mainly used for developing applications for Android, iOS, and Web. So, today we will be checking out the 13 most asked React Native questions. The problem with keyboard keyboard in React Native gets more severe if you have keyboard with no way to dismiss it as a result of tapping on it while the keyboard is up will only dismiss the correct keyboard. React Native allows you to use ReactJS to build your components, and implements ReactJS under the hood.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - The FAQs of React Native
Kiran HackerNoon profile picture

React Native is a framework created by Facebook that is used for building native apps using React. It is mainly used for developing applications for Android, iOS, and Web. It an open-source framework. So, today we will be checking out the 13 most asked React Native questions.

13 Most Asked React Native Questions

1. What is the difference between React Native and React?

Answer:

ReactJS is a JavaScript library, supporting both front-end web and being run on a server, for building user interfaces and web applications. React Native
is a mobile framework that compiles to native app components, allowing you to build native mobile applications for different platforms (iOS, Android, and Windows Mobile) in JavaScript that allows you to use ReactJS to build your components, and implements ReactJS under the hood. Both follow the JSX syntax extension to JavaScript. Both are open-sourced by Facebook.

2. What is the difference between using constructor vs getInitialState in React / React Native?

Answer: 

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the

getInitialState
method when using
React.createClass
. See the official React doc on the subject of ES6 classes.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}

is equivalent to

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

3. How to fix error while running React Native app from terminal (iOS)?

Answer: You can check out this link (Running react-native run-ios occurs an error?). It appears to be a problem with the location of

Command line tools
. In Xcode, select the Xcode menu, then Preferences, then Locations tab. Select your Xcode version from the dropdown and exit Xcode.

Alternative Answer: 

You may need to install or set the location of the Xcode Command Line Tools

Via command line 

If you have Xcode downloaded you can run the following to set the path:

sudo xcode-select -s /Applications/Xcode.app

If the command line tools haven’t been installed yet, you may need to run this first:

xcode-select --install

You may need to accept the Xcode license before installing command-line tools:

sudo xcodebuild -license accept

4. How to fix error “Unable to load script from assets index.android.bundle” on Windows?

Answer: 

This issue will help you to resolve the problem in the following steps.

  • (in the project directory)
    mkdir android/app/src/main/assets
  • react-native bundle --platform android --dev false --entry-file index.js --bundle-output 
    android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
  • react-native run-android

You can automate the above steps by placing them in

scripts
part of
package.json
like this:

"android-linux": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android"

Then you can just execute

npm run android-linux
from your command line every time.

Alternative Answer: 

If You are running your application on a physical device and getting this error

unable to load script from assets index.android.bundle

try running the command:

adb reverse tcp:8081 tcp:8081

5. How to fix error “React Native android build failed. SDK location not found”?

Answer:

  • Go to the
    android/ 
    directory of your react-native project
  • Create a file called
    local.properties
    with this line:
  • sdk.dir = /Users/USERNAME/Library/Android/sdk

Where

USERNAME
is your macOS username.

Alternative Answer:

  • Go to your React-native Project -> Android
  • Create a file
    local.properties
  • Open the file
  • paste your Android SDK path like below

    - In Windows
    sdk.dir = C:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk


    - In macOS
    sdk.dir = /Users/USERNAME/Library/Android/sdk


    - In Linux
    sdk.dir = /home/USERNAME/Android/Sdk

Replace USERNAME with your user name. 

Now, Run the

react-native run-android
in your terminal.

6. How to hide keyboard in React Native?

Answer: The problem with keyboard not dismissing gets more severe if you have

keyboardType='numeric'
, as there is no way to dismiss it. 

Replacing View with ScrollView is not a correct solution, as if you have multiple

textInput
s or
button
s, tapping on them while the keyboard is up will only dismiss the keyboard. 

The correct way is to encapsulate View with

TouchableWithoutFeedback
and calling
Keyboard.dismiss()

You can now use

ScrollView
with
keyboardShouldPersistTaps='handled' 
to only dismiss the keyboard when the tap is not handled by the children (ie. tapping on other textInputs or buttons) If you have

<View style={{flex: 1}}>
    <TextInput keyboardType='numeric'/>
</View>

Change it to

<ScrollView contentContainerStyle={{flexGrow: 1}}
  keyboardShouldPersistTaps='handled'
>
  <TextInput keyboardType='numeric'/>
</ScrollView>

or

import {Keyboard} from 'react-native'

<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
    <View style={{flex: 1}}>
        <TextInput keyboardType='numeric'/>
    </View>
</TouchableWithoutFeedback>

You can also create a Higher Order Component to dismiss the keyboard.

import React from 'react';
import { TouchableWithoutFeedback, Keyboard, View } from 'react-native';

const DismissKeyboardHOC = (Comp) => {
  return ({ children, ...props }) => (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
      <Comp {...props}>
        {children}
      </Comp>
    </TouchableWithoutFeedback>
  );
};
const DismissKeyboardView = DismissKeyboardHOC(View)

Simply use it like this

...
render() {
    <DismissKeyboardView>
        <TextInput keyboardType='numeric'/>
    </DismissKeyboardView>
}

Note: The

accessible={false}
is required to make the input form continue to be accessible through VoiceOver. 

Alternative Answer: 

This got updated and documented. No more hidden tricks.

import { Keyboard } from 'react-native'

// Hide that keyboard!
Keyboard.dismiss()

https://github.com/facebook/react-native/pull/9925

7. How to fix error “Application has not been registered”?

Answer: 

It is an error caused by not matching the name of project and your registered component. 

You have inited project with one name, i.e. 

react-native init AwesomeApp 

But in your index.ios.js file, you register other component

AppRegistry.registerComponent('Bananas', () => Bananas);

When it must be 

AppRegistry.registerComponent('AwesomeApp', () => Bananas);

Try to fix it. 

Alternative Answer: 

Most of the time the problem is that you have another

react-native start
(i.e. React Native Packager) server running either on another terminal or another tab of TMUX (if you are using TMUX). 

You need to find that process and close it, so after running

react-native run-ios
for instance, it will establish a new packager server that registered for that specific application. Just find that process using:

ps aux | grep react-native

Find the process id (PID) and kill the packager process using

kill
command (e.g.
kill -9 [PID]
). You should find the
launchPackager.command
app in macOS, not sure about the other operating systems. 

Then try to run the

run-ios
(or android) again. You should be able to see the new path after running the new packager server, e.g.:

Looking for JS files in
   /Users/afshin/Desktop/awesome-app

8. How to add icons to the React Native app?

Answer: 

iOS Icons

  • Set
    AppIcon
    in
    Images.xcassets
    .
  • Add 9 different size icons:

    - 29pt
    - 29pt*2
    - 29pt*3
    - 40pt*2
    - 40pt*3
    - 57pt
    - 57pt*2
    - 60pt*2
    - 60pt*3.

Images.xcassets will look like this: 

Android Icons

  • Put
    ic_launcher.png
    in folders
     [ProjectDirectory]/android/app/src/main/res/mipmap-*/
    .

    - 72*72
    ic_launcher.png in mipmap-hdpi
    .
    - 48*48
    ic_launcher.png in mipmap-mdpi
    .
    - 96*96
    ic_launcher.png in mipmap-xhdpi
    .
    - 144*144
    ic_launcher.png in mipmap-xxhdpi
    .
    - 192*192
    ic_launcher.png in mipmap-xxxhdpi
    .

Update 2019 Android 

The latest versions of React Native also supports the round icon. For this particular case, you have two choices: 

a. Add round icons: In each mipmap folder, add additionally to the

ic_launcher.png
file also a round version called
 ic_launcher_round.png
with the same size. 

b. Remove round icons: Inside

yourProjectFolder/android/app/src/main/AndroidManifest.xml
remove the line
android:roundIcon="@mipmap/ic_launcher_round"
and save it. 

Otherwise, the build throws an error.

9. How to combine multiple inline style objects?

Answer: 

If you’re using React Native, you can use the array notation:

<View style={[styles.base, styles.background]} />

Check out blog post about this in detail. 

Alternative Answer: 

You can use the spread operator:

 <button style={{...styles.panel.button,...styles.panel.backButton}}>Back</button

10. How to change the default iOS simulator device?

Answer: 

Specify a simulator using the

--simulator
flag. 

These are the available devices for iOS 12.0:

react-native run-ios --simulator="iPhone 5s"
react-native run-ios --simulator="iPhone 6"
react-native run-ios --simulator="iPhone 6 Plus"
react-native run-ios --simulator="iPhone 6s"
react-native run-ios --simulator="iPhone 6s Plus"
react-native run-ios --simulator="iPhone 7"
react-native run-ios --simulator="iPhone 7 Plus"
react-native run-ios --simulator="iPhone 8"
react-native run-ios --simulator="iPhone 8 Plus"
react-native run-ios --simulator="iPhone SE"
react-native run-ios --simulator="iPhone X"
react-native run-ios --simulator="iPhone XR"
react-native run-ios --simulator="iPhone Xs"
react-native run-ios --simulator="iPhone Xs Max"
react-native run-ios --simulator="iPad Air"
react-native run-ios --simulator="iPad Air 2"
react-native run-ios --simulator="iPad"
react-native run-ios --simulator="iPad Pro"
react-native run-ios --simulator="iPad Pro"
react-native run-ios --simulator="iPad Pro"
react-native run-ios --simulator="iPad Pro"
react-native run-ios --simulator="iPad"

List all available iOS devices:

xcrun simctl list devices

There is currently no way to set a default. 

React Native Docs: Running On Simulator 

Alternative Answer: 

You can also use npm for this by adding an entry to the

scripts
element of your
package.json
file. 

E.g.

"launch-ios": "react-native run-ios --simulator \"iPad Air 2\""

Then to use this:

npm run launch-ios

11. How to do logging in React Native?

Answer: 

console.log
works. 

By default on iOS, it logs to the debug pane inside Xcode. 

From the IOS simulator press (

⌘+D
) and press Remote JS Debugging. This will open a resource, http://localhost:8081/debugger-ui on the localhost. From there use Chrome Developer tools javascript console to view
console.log

Alternative Answer: 

Use

console.log, console.warn
etc. 

As of React Native 0.29, you can simply run the following to see logs in the console:

$ react-native log-ios
$ react-native log-android

12. How to insert a line break into a <Text> component in React Native?

Answer: 

This should do it:

<Text>
Hi~{"\n"}
this is a test message.
</Text>

Alternative Answer: 

You can also do:

<Text>{`
Hi~
this is a test message.
`}</Text>

By doing this, you don’t have to insert stuff within the string; just wrap it once and it keeps all your line-breaks.

13. What is the difference between react-native-firebase and react-redux-firebase?

Answer: 

Main difference:

  • react-redux-firebase
    – for using Firebase with Redux
  • react-native-firebase
    – for using Firebase JS API with react-native

react-redux-firebase
actually supports using
react-native-firebase
.
react-native-firebase
provides the Firebase JS API while using native-modules under the hood, meaning you can provide that as your Firebase instance to
react-redux-firebase
like so:

import { compose, createStore } from 'redux';
import RNFirebase from 'react-native-firebase';
import { getFirebase, reactReduxFirebase } from 'react-redux-firebase';
import thunk from 'redux-thunk';
import makeRootReducer from './reducers';

const reactNativeFirebaseConfig = {
  debug: true
};

const reduxFirebaseConfig = {
  userProfile: 'users', // save users profiles to 'users' collection
};

export default (initialState = { firebase: {} }) => {
  // initialize firebase
  const firebase = RNFirebase.initializeApp(reactNativeFirebaseConfig);

  const store = createStore(
    makeRootReducer(),
    initialState,
    compose(
      reactReduxFirebase(firebase, reduxFirebaseConfig), // pass initialized react-native-firebase app instance
     // applyMiddleware can be placed here
    )
  );

  return store;
};

This setup and more are covered in the react-native recipes section of the docs

In Conclusion 

These are the 13 most commonly asked React Native questions. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you. 

Hope this article helped you.

This post was originally posted on DevPost by Truemark.

Previously published at https://thedevpost.com/blog/13-most-asked-react-native-questions/