React Native Cheat Sheet
by Bochrak via [Link]/200241/cs/42327/
Development environment Set-up Expo (cont)
Expo For beginners Expo A web-based playground where you can write React
Simplifies the setup process Snack Native snippets and run them in the browser.
Provides OTA updates Expo For establishing a connection that allows devices to access
Does not allow you to add custom native code Tunnel the app even if they're not on the same wireless network.
Expo apps tend to have larger sizes npx expo start --tunnel
React Native For Experienced Developers
CLI Supports integrating custom native modules Finding Libraries
Potentially better performance for complex
React Native Directory is a searchable database of libraries built
applications
specifically for React Native.
Requires Xcode or Android Studio to get
started.
StyleSheet
No OTA updates.
An abstraction similar to CSS StyleSheets.
Creating an app Declare styles in a structured and optimized manner.
You can use an array of styles to combine multiple style objects-
Initialize a new project npx create-expo-app my-app
the last style in the array has precedence, or mix predefined styles
Start development server cd my-app with inline styles.
npm start All of the core components accept a prop named style .
import React from 'react';
Running app import {StyleSheet, Text, View} from 'react-native'
Android Use the Expo Go app to scan the QR code from your ;
terminal to open your project. const App = () => (
iPhone Use the built-in QR code scanner of the default iOS <View style={[Link]}>
Camera app. <Text style={[styles.baseText, [Link]
]}>
Connect to the same wireless network as your computer.
This is bold and black text
Metro </Text>
<Text style={[styles.baseText, { color: 'blue'
When you run your app, the Expo CLI starts Metro Bundler. It's a
}]}>
JavaScript bundler that takes all your JavaScript files and assets,
This is blue and normal weight text
bundles them, and transforms them using Babel. This process
</Text>
converts the code into a format that can be executed by the platform
running the app (iOS or Android). </View>
);
Expo const styles = StyleSheet.create({
container: { flex: 1,
Expo A set of tools and services to make development with React
padding: 24,
Native easier.
backgroundColor: '#eaeaea' },
Expo A modular set of packages that provides access that
baseText: { fontSize: 16,
SDK provides access to native APIs, like Camera or Notifications.
color: 'black' },
Expo A command-line tool that is the primary interface between a
boldText: { fontWeight: 'bold' }
CLI developer and other Expo tools.
}
Expo An open-source sandbox app you can download on your );
Go phone to view your app in development.
export default App;
UseColorScheme Hook
Provides and subscribes to color scheme updates from the
appearance module in react native.
It returns the current color scheme preference of the user's
device.
Supported color schemes: "light", "dark", null.
import React from 'react';
import
{Text, StyleSheet, useColorScheme, View}
from 'react-native';
const App = () => {
const colorScheme = useColorScheme();
return (
<View style={[Link]}>
<Text>useColorScheme(): {colorScheme}</Tex
t>
</View>
);
};
const styles = [Link]({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'}});
export default App;
By Bochrak Published 11th February, 2024. Sponsored by [Link]
[Link]/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 1 of 10. Yours!
[Link]
React Native Cheat Sheet
by Bochrak via [Link]/200241/cs/42327/
useWindowDimensions Hook Pressable (cont)
Used to get the dimensions of the device window. props:
It returns an object containing the window's width and height. onPressIn: method called when a press is activated.
Useful for creating responsive designs and layouts that adapt to different onPressOut: method called when the press gesture is
screen sizes. deactivated.
import React from 'react'; onLongPress: method called when user leaves their finger longer
import than 500 milliseconds before removing it, customize this time period
using the delayLongPress prop.
{View, StyleSheet, Text, useWindowDimensions}
pressed: state that refers to a boolean value provided to the style
from 'react-native';
and children functions of Pressable, to check if component is being
const App = () => {
pressed.
const {height,width,scale,fontScale}=useWindowDimensions();
hitSlop: prop to increase the area where touch gestures are
return (
recognized. (extended interactive area "HitRect").
<View style={[Link]}>
pressRetentionOffset: prop to specify the area in which the touch
<Text>Window Dimension Data</Text>
can move while maintaining the press's active state. ("PressRect").
<Text>Height: {height}</Text>
<Text>Width: {width}</Text> Navigation
<Text>Font scale: {fontScale}</Text>
React Navigation
<Text>Pixel ratio: {scale}</Text>
React Native does not come with built-in navigation capabilities.
</View>
React Navigation is the most popular third-party library.
);
Enable developers to implement various navigation patterns.
};
Provides a set of navigators, such as stack, tab, and drawer
const styles = [Link](
navigators.
container: {
flex: 1,
Stack Navigator
justifyContent: 'center',
alignItems: 'center'},
});
export default App;
Button
A basic button component that should render on any platform.
Supports a minimal level of customization.
import React from 'react';
import { View, Button } from 'react-native';
const ExampleButton = () => {
const handlePress = () => {console.log('Button pressed');};
return (
<View>
<Button title="Click Me" onPress={handlePress} color="#84
1584"/>
</View>
);
};
export default ExampleButton;
Required props: title and onPress
Pressable
Used for users press interactions. Allows transition between screens where each new screen is
Detects various stages of press interactions on any of its child components.
placed on top of a stack.
Highly customizable and flexible way to handle touch-based input. NavigationContainer: Component container for your app's
Inherits all the styles of the View component. navigation structure.
import React from 'react'; Manages the navigation tree and contains the navigation state.
import { Pressable, Text } from 'react-native'; Should be only used once in your app at the root.
const ExamplePressable = () => { createNativeStackNavigator: Function that returns an object
return ( containing two properties.
<Pressable onPress={() => console.log('Pressed!')} Navigator: Takes Screen elements as its children to define the
style={({ pressed }) => [ configuration for routes.
initialRouteName: prop for the Navigator specify what the initial route
{backgroundColor: pressed ? 'lightskyblue' : 'lightgra
y'}, in a stack is.
{padding: 10, alignItems: 'center' }]} screenOptions: prop to Navigator to specify common options.
Screen: Component takes 2 required props name and
hitSlop={{top: 10, bottom: 10, left: 10, right: 10 }}
component.
pressRetentionOffset={{top: 20, bottom: 20, left: 20}} >
name: prop which refers to the name of the route.
<Text>Press Me</Text>
component: prop which specifies the component to render for the
</Pressable>
route.
);
options: prop to Screen to specify screen-specific options.
};
navigation and route props: are automatically provided to each
export default ExamplePressable;
screen component by the navigator.
navigation: prop is available to all screen components and allows
you to control navigation actions.
route: prop contains information about the route, including
parameters passed to that screen.
You can read the params through route.params inside a screen.
Params should contain the minimal data required to show a screen.
By Bochrak Published 11th February, 2024. Sponsored by [Link]
[Link]/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 2 of 10. Yours!
[Link]
React Native Cheat Sheet
by Bochrak via [Link]/200241/cs/42327/
Stack Navigator (cont) Drawer Navigator (cont)
import * as React from 'react';
import * as React from 'react'; import { View, Text} from 'react-native';
import { View, Text, Button } from 'react-native'; import { NavigationContainer } from '@react-navigation/n
import { createStackNavigator } from '@react-navigation/stack';
import { createDrawerNavigator } from '@react-navigatio
import { NavigationContainer } from '@react-navigation/native';
function CustomDrawerContent() {
const HomeScreen = ({ navigation }) => { return (
return ( <DrawerContentScrollView {...props}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'
<Text> Welcome}}>
</Text>
<Text>Home Screen</Text> <DrawerItemList {...props} />
<Button title="Go to Details" <DrawerItem label="Help" onPress={() => alert('L
onPress={() => navigation.navigate('Details', { someParam: 'Hello!' })} />
</DrawerContentScrollView>
</View> );
); }
}; function HomeScreen() { // ... }
const DetailsScreen = ({ route }) => { function NotificationsScreen() { // ... }
return ( const Drawer = createDrawerNavigator();
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'
function App() { }}>
<Text>Details Screen</Text> return (
<Text>Parameter: {[Link]}</Text> <NavigationContainer>
</View> <Drawer.Navigator initialRouteName="Home"
); screenOptions={{drawerPosition: 'left'
}; drawerContent={props => <CustomDrawer
const Stack = createStackNavigator(); <Drawer.Screen name="Home" component={HomeScr
function App() { <Drawer.Screen name="Notifications" component
return ( [Link]>
<NavigationContainer> </NavigationContainer>
<St[Link]vigator initialRouteName="Home" );
screenOptions={{ headerStyle: {backgroundColor:
} '#f4511e'}}} >
<St[Link] name="Home" component={HomeScreen} options={{
export title: 'My Home' }} />
default App;
<St[Link] name="Details" component={DetailsScreen}
The following options={{ title: 'Detail Vie
are also available:
w' }} /> navigation. jumpTo('RouteName'): go to a specific screen in the drawer navi
</Stack.Navigator> navigation. openDrawer: open the drawer.
</NavigationContainer> navigation.closeDrawer: close the drawer.
); navigation.toggleDrawer: toggle the state, ie. switch from closed to open and
}
export default App; Tab Navigator
Navigation actions:
navigation.navigate('RouteName'): Pushes a new route to the native stack navigator if it's not already in the stack.
If you navigate to a route that is not defined in the navigator, it will print an error in the development mode and will not show
errors in production mode.
navigation.push('RouteName'): Used to navigate to a screen in the stack navigator, adding a new route to the navigation
regardless of the existing navigation history.
navigation.goBack(): Is used to programmatically go back to the previous screen.
navigation.popToTop(): Used to go back to the first screen in the stack.
Drawer Navigator
Renders a navigation drawer on the side of the screen which can Common style of navigation.
be opened and closed via gestures. Can be tabs on the bottom of the screen or on the top below the header.
You cannot use the useNavigation hook inside the drawerContent Bottom tab navigation: A simple tab bar on the bottom of the screen that lets
since useNavigation is only available inside screens. You get a different routes.
navigation prop for your drawerContent which you can use instead.
Routes are lazily initialized -- their screen components are not mounted until
drawerPosition: prop typically set in the screenOptions to specify
You cannot use the useNavigation hook inside the tabBar since useNavigati
the position of the drawer, such as left or right.
screens. You get a navigation prop for your tabBar which you can use instead.
drawerContent: prop in the Drawer Navigator that allows you to
provide a custom component for the drawer's content.
import React from 'react';
CustomDrawerContent: refer to a user-defined React component import { View, Text } from 'react-native';
that is passed to the drawerContent prop.
import { NavigationContainer } from '@react-navigation/n
DrawerItem: in a custom drawer allows for more flexibility and import { createBottomTabNavigator } from '@react-navig
customization compared to defining routes directly in the navigator. ;
import Ionicons from 'react-native-vector-icons/Ion
const HomeScreen = () => {
return(
<View>
<Text>Home Screen</Text>
</View>
)
};
const SettingsScreen = () => {
return(
<View>
<Text>Settings Screen</Text></View>
)
}
const Tab = createBottomTabNavigator();
function App() {
return (
<NavigationContainer>
<Tab.Navigator screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
if ([Link] === 'Home') {
iconName = focused ? 'ios-home' : 'ios-home-outline';
} else if ([Link] === 'Settings') {
iconName = focused ? 'ios-settings' : 'ios-setting
return <Ionicons name={iconName} size={size} color
)} >
<Tab.Screen name="Home" component={HomeScreen} /
<Tab.Screen name="Settings" component={Setting
</[Link]>
</NavigationContainer>
);
}
export default App;
By Bochrak Published 11th February, 2024. Sponsored by [Link]
[Link]/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 3 of 10. Yours!
[Link]
React Native Cheat Sheet
by Bochrak via [Link]/200241/cs/42327/
Tab Navigator (cont) ScrollView (cont)
The following are also available: import React from 'react';
navigation.jumpTo('RouteName'): is a method that directly import { ScrollView, Text, View } from 'react-native';
switches to a specified screen within the tab navigator. const ExampleScrollView = () => {
return (
View <ScrollView indicatorStyle={"white"}
A container that supports layout with flexbox, style, some touch handling, and accessibility controls. flex: 1 }}
style={{
Like a <div> in HTML. horizontal={true}> {/ horizontal scrolling
Designed to be nested inside other views and can have 0 to many children<Text>Item
of any type. 1</Text> {/ Repeat more components for more
import React from 'react';
import { View, Text } from 'react-native'; </ScrollView>
const ExampleView = () => { );
return ( };
export default
<View style={{ flex: 1, justifyContent: 'center', alignItems: ExampleScrollView;
'center' }
}> Performance Issues with Large Lists: Slow rendering times for
<Text>Hello from View!</Text> large lists.
</View> Memory Consumption: Consume a significant amount of memory
); with large lists or complex item views.
};
export default ExampleView; FlatList
Used to efficiently render long lists.
Text Offers features like pull-to-refresh, infinite scrolling, and easy item separator
Lazy rendering: renders items only when they appear on the screen and are
user scrolls away from them.
Internal state is not preserved when content scrolls out of the render window
Inherits the props of the ScrollView component.
import React from 'react';
import { FlatList, Text, View } from 'react-native';
const ExampleFlatList = () => {
const data = [{ id: '1', name: 'Item 1' }, { id: '2', name:
return (
<FlatList data={data}
renderItem={({ item }) => <Text>{[Link]}</Text>
keyExtractor={item => [Link]} />
);
};
export default ExampleFlatList;
Two required props:
data: accepts a plain array that contains the list of items to display.
renderItem: a function that goes over each item in the array and renders it in
keyExtractor: It instructs the list to use the id of each item as React keys
property.
SectionList
A component for displaying text. Used for rendering large lists with section headers.
Supports nesting, styling, and touch handling. Uses lazy rendering to achieve faster rendering.
Everything inside it is no longer using the Flexbox layout but Inherits the props of the ScrollView component.
using text layout. Internal state is not preserved when content scrolls out of the render window
Elements inside it are no longer rectangles, but wrap at the end of Provides support for section headers and section separators.
the line. import React from 'react';
import React from 'react'; import { SectionList, Text, View } from 'react-native';
import { Text } from 'react-native'; const ExampleSectionList = () => {
const ExampleText = () => { const sections = [ { title: 'Section 1', data: ['Item 1', '
return ( { title: 'Section 2', data: ['Item 3', '
<Text style={{ fontSize: 18, color: 'blue' }}> return (
Hello, this is a Text component! <SectionList
</Text> sections={sections}
); renderItem={({ item }) => <Text>{item}</Text
}; renderSectionHeader={({ section }) => <Text>{
export default ExampleText; }</Text>}
You must wrap all the text nodes inside of a <Text> component keyExtractor={(item, index) => item + index} />
);
Will raise exception
<View> Some text </View> };
export default ExampleSectionList;
Correct
<View>
<Text> Some text </Text>
</View>
Text container: Text will be inline if the space allow it, otherwise,
text will flow as if it was one.
<Text>
<Text>First part and </Text>
<Text>second part</Text>
</Text>
First part and second part
View container:
Each text is its own block, otherwise, the text will flow in its own
block.
<View>
<Text>First part and </Text>
<Text>second part</Text>
</View>
First part and
second part
ScrollView
Creates a scrollable area when content exceeds screen's physical
limits.
Can contain multiple components and views.
Can be scrolled vertically or horizontally.
Must have a bounded height in order to work.
Renders all its react child components at once.
By Bochrak Published 11th February, 2024. Sponsored by [Link]
[Link]/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 4 of 10. Yours!
[Link]
React Native Cheat Sheet
by Bochrak via [Link]/200241/cs/42327/
SectionList (cont)
Two required props:
sections : accepts the array that contains the list of items to
display, akin to the data prop in FlatList.
renderItem: method which acts as the default renderer for every
item in each section.
renderSectionHeader: prop, render each section’s header.
TextInput
Used for inputting text into the app via a keyboard.
import React, { useState } from 'react';
import { TextInput } from 'react-native';
const ExampleTextInput = () => {
const [inputValue, setInputValue] = useState('');
return (
<TextInput value={inputValue}
onChangeText={text => setInputValue(text)}
placeholder="Enter text here"
style={{ height: 40, borderWidth: 1, margin: 10 }} /
>
);
};
export default ExampleTextInput;
Image
Used for displaying different types of images,
network images, static resources, temporary local images,
and images from local disk, such as the camera roll.
You can also add style to an image.
import React from 'react';
import { Image } from 'react-native';
const ExampleImage = () => {
return (
<>
{/ Remote Image /}
<Image source={{ uri: 'https://example.com/image.j
pg' }}
style={{ width: 200, height: 200 }}
resizeMode="contain" />
{/ Local Image /}
<Image source={require('./[Link]')}
style={{ width: 200, height: 200 }}
resizeMode="cover" />
</>
);
};
export default ExampleImage;
resizeMode :
'cover': Scales image to fill the container, maintaining its aspect ratio.
'contain': Scales image to fit inside the container, maintain the image's
aspect ratio ensuring the entire image is visible.
'stretch': Stretches image to fill the container, possibly distorting the aspect
ratio.
'center': Centers image in the container without scaling. 'repeat': Repeats
the image to cover the container.
For network and data images, you must specify the dimensions of
the image.
By Bochrak Published 11th February, 2024. Sponsored by [Link]
[Link]/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 5 of 10. Yours!
[Link]