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.
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.
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 */ };
},
});
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
Answer:
This issue will help you to resolve the problem in the following steps.
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
Answer:
android/
directory of your react-native projectlocal.properties
with this line:sdk.dir = /Users/USERNAME/Library/Android/sdk
Where
USERNAME
is your macOS username.Alternative Answer:
local.properties
sdk.dir = C:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk
sdk.dir = /Users/USERNAME/Library/Android/sdk
sdk.dir = /home/USERNAME/Android/Sdk
Replace USERNAME with your user name.
Now, Run the
react-native run-android
in your terminal.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
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
Answer:
iOS Icons
AppIcon
in Images.xcassets
.Images.xcassets will look like this:
Android Icons
ic_launcher.png
in folders [ProjectDirectory]/android/app/src/main/res/mipmap-*/
.ic_launcher.png in mipmap-hdpi
.ic_launcher.png in mipmap-mdpi
.ic_launcher.png in mipmap-xhdpi
.ic_launcher.png in mipmap-xxhdpi
.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.
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
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
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
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.
Answer:
Main difference:
react-redux-firebase
– for using Firebase with Reduxreact-native-firebase
– for using Firebase JS API with react-nativereact-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/