This is a collection of React Native recipes, code snippets, and styling tips and tricks.
Table of contents
Command Line
Getting Started
To get started with React Native refer to 3 Steps to Build Your First Mobile App with React Native. It explains the basics and how to set up required software to get started.
Creating Project
Open Terminal App and execute these commands to initialize a new project.
react-native init AppName;
cd AppName;
Running App in the iOS Simulator
To run your app in the iOS simulator execute in terminal:
react-native run-ios;
Running App in the Android Simulator
To run your app in the iOS simulator execute in terminal:
cd AppName;
react-native run-android;
Specifying a Simulator Device
To run on iPhone 7 Plus in the simulator execute:
react-native run-ios --simulator "iPhone 7 Plus"
To list available devices execute:
xcrun simctl list devices
Linking Dependencies
Sometimes you need to link dependencies of 3rd party libraries. Suppose you installed react-native-vector-icons library. And then, to add icons fonts to your project you would execute:
react-native link
Linking Libraries
Detailed instructions on linking libraries available at Linking Libraries on React Native documentation site.
If you’re using libraries such as Linking
or PushNotificationIOS
, you need to add Header Search Paths.
Here is how to add a path to the libraries that come with React Native.
- Open
AppName.xcodeproj
inios
folder. - Click
AppName
in the left panel. - Click
AppName
inTARGETS
section. - Click
Build Settings
. - Search for
Header Search Path
row insideSearch Paths
sections. - Double-click on a path in
AppName
column. - Click
+
button in the left bottom corned of popped up window. - Paste
$(SRCROOT)/../node_modules/react-native/Libraries
into the first column and chooserecursive
from a dropdown menu in the second column.
Upgrading React Native
To upgrade React Native to the latest version execute:
npm install --save react-native@latest;
To upgrade project files execute:
react-native upgrade;
Upgrading NPM Packages
To list all outdated packages execute:
npm outdated
To update a package to the latest version execute:
npm install --save package-name@latest;
Development Flow
Enabling Hot Reloading
Once enabled, hot reloading will refresh your app in the simulator every time you make a change to the code.
To enable hot reloading launch your app in the simulator first. Once it’s up, press either ⌘D if you’re running iOS simulator or ⌘M if you’re running Android simulator, and select Enable Hot Reloading.
Enabling Remote Debugging
Once enabled, remote debugging will open up a new tab in Chrome with instructions on how to open Developer Tools that will show debug information, such as errors and warnings. You can also output custom data, including strings, variables, objects, components, etc., using console.log('Debug', object)
in your app’s code.
To enable remote debugging launch your app in the simulator first. Once it’s up, press either ⌘D if you’re running iOS simulator or ⌘M if you’re running Android simulator, and select Debug JS Remotely.
Code Snippets
Detecting Screen Size
Sometimes you may need to know what’s the screen size of a device that your app is running on to adjust the layout, font sizes, etc.
import { Dimensions } from 'react-native';
const { width, height } = Dimensions.get('window');
alert(Screen size: ${width}x${height});
Here are various screen sizes for your reference:
- iPhone 5
320 x 568 - iPhone 6
375 x 667 - iPhone 6 Plus
414 x 736
Transforming Text
To transform text to upper case use toUpperCase()
method of string variables.
<Text>{this.props.title.toUpperCase()}</Text>
To transform text to lower case use toLowerCase()
method of string variables.
<Text>{this.props.title.toLowerCase()}</Text>
Limiting Number of Lines for Text Component
To limit the number of lines shown for Text
component and cut the text that doesn’t fit use numberOfLines
prop.
<Text numberOfLines={2}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tincidunt eu neque non varius. Phasellus id arcu in enim sodales sodales. Vestibulum maximus hendrerit feugiat. Maecenas nec risus metus. Nam ullamcorper et mauris sit amet placerat. Cras elementum nunc a lorem auctor accumsan. Nam dapibus tristique tempor. Aenean nec augue viverra, tincidunt magna ac, varius leo. Nunc condimentum tristique placerat. Donec ullamcorper nibh vel lacinia pharetra. Praesent a scelerisque tellus. Fusce aliquet porta scelerisque. Suspendisse convallis urna eu arcu finibus ullamcorper. Etiam commodo faucibus ligula, ac consectetur mauris gravida id. Quisque lacus tortor, pellentesque sed eleifend nec, pellentesque vitae diam.
</Text>
Components
Component Boilerplate
You can use this boilerplate to create new components.
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
export default class Component extends Component {
render() {
return (
<View style={styles.container}>
<Text>Component</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
Default Prop Values
To set default prop values for you components use defaultProps
property. In the example below we set the default value for title
prop. You can always override the default value by passing a custom value to the component JSX expression. For example, <Header title="My Header" />
, would change title
value from default one to My Header.
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
export default class Header extends Component {
static defaultProps = {
title: 'Default Header'
}
render() {
return (
<View >
<Text style={styles.header}>
{this.props.title.toUpperCase()}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
header: {
fontFamily: 'Avenir',
fontSize: 40,
fontWeight: 'bold',
textAlign: 'center',
},
});
Spread Attributes
You can have props as an object and pass them in JSX using ...
spread operator.
render() {
const props = {
title: 'My Title',
size: 20,
};
return <Header {...props} />;
}
This code is essentially the same as follows:
render() {
return <Header title="My Title" size={20} />;
}
Pulling Properties out of Objects
You can pull properties out of objects using const { prop1, prop1, ...rest } = object
notation.
render() {
const { title, size, ...rest } = this.props;
return (
<View>
<Text style={[styles.header, { fontSize: size }]} {...rest}>
{title.toUpperCase()}
</Text>
</View>
);
}
Using ES7 Decorators
Install babel-plugin-transform-decorators-legacy
first.
npm install --save-dev babel-plugin-transform-decorators-legacy
And then edit .babelrc
file to include transform-decorators-legacy
plugin.
{
"presets": [
"react-native"
],
"plugins": [
"transform-decorators-legacy"
]
}
Now you can use decorators. In the following example we’re using @connect
decorator from react-redux
package.
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
@connect(
(state) => {
const { user, data } = state;
return {
user,
data
};},
(dispatch) => ({
actions: { ...bindActionCreators({ actionA, actionB }, dispatch) }
})
)
export default class App extends Component {
render({ user } = this.props) {
return (
<View >
<Text style={styles.header}>
Hello {user.name}
</Text>
</View>
);
}
}
Styling
Applying Multiple Styles to a Component
You can use an array to pass multiple styles to a component.
<View style={[styles.generic, styles.specific, { color: 'blue' }]} />
Making a Circle
The trick is to use width/height of your circle divided by 2 for borderRadius
.
<View style={{
width: 90,
height: 90,
borderRadius: 90 / 2,
backgroundColor: '#2196F3'
}}/>
Fitting Image Into Flexible Container
Suppose you have a flexible container and want to fit an image into it, so it takes all of the container space and centered both, vertically and horizontally. Here is how you do it:
<View style={{
backgroundColor: '#dddddd',
flex: 1,
}}>
<Image source={{ uri: 'https://placekitten.com/g/800/600' }} style={{
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
}} />
</View>
Flexbox
Primary and Secondary Axis
In flexDirection
default column
mode the primary axis is column, the secondary is row, and vice versa in row
mode.
Justify Content
Adding justifyContent
to a component’s style sets the distribution of children along the primary axis. Available options are
flex-start
(default) — Children distributed at the start.
container: {
flexDirection: 'row',
justifyContent: 'flex-start'
}
center
— Children are centered.
container: {
flexDirection: 'row',
justifyContent: 'center'
}
flex-end
— Children distributed at the end.
container: {
flexDirection: 'row',
justifyContent: 'flex-end'
},
space-around
— Children distributed with equal space around them.
container: {
flexDirection: 'row',
justifyContent: 'space-around'
}
space-between
— Children distributed evenly.
container: {
flexDirection: 'row',
justifyContent: 'space-between'
}
Align Items
Adding alignItems
to a component’s style sets the alignment of children along the secondary axis. Available options are
flex-start
— Children aligned at the start.
container: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start'
}
center
— Children aligned at the center.
container: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
}
flex-end
— Children aligned at the end.
container: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-end'
}
stretch
(default) — Children stretched to fill up all space. This options doesn’t work for children with fixed dimension along the secondary axis.
Wrapping Up
I hope you were able to find something useful for you and saved some time for developing amazing apps. If you feel like the list is missing something, just leave a comment and I’ll add it.