Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
31 views10 pages

React Native

The React Native Cheat Sheet provides a comprehensive overview of setting up a development environment using Expo and React Native CLI, highlighting their respective advantages and limitations. It includes instructions for creating an app, running it on devices, and utilizing various components such as StyleSheet, Pressable, and navigation methods. Additionally, it covers hooks like useColorScheme and useWindowDimensions, and outlines navigation patterns including Stack, Drawer, and Tab Navigators.

Uploaded by

edelisakson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views10 pages

React Native

The React Native Cheat Sheet provides a comprehensive overview of setting up a development environment using Expo and React Native CLI, highlighting their respective advantages and limitations. It includes instructions for creating an app, running it on devices, and utilizing various components such as StyleSheet, Pressable, and navigation methods. Additionally, it covers hooks like useColorScheme and useWindowDimensions, and outlines navigation patterns including Stack, Drawer, and Tab Navigators.

Uploaded by

edelisakson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

React Native Cheat Sheet

by Bochrak via cheatography.com/200241/cs/42327/

Develo​pment enviro​nment 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 establ​ishing 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 Experi​enced Developers
CLI  Supports integr​ating custom native modules Finding Libraries
 Potent​ially better perfor​mance for complex
 React Native Directory is a searchable database of libraries built
applications
specif​ically for React Native.
 Requires Xcode or Android Studio to get
started.
StyleSheet
 No OTA updates.
 An abstra​ction 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​-ex​po-app my-app
the last style in the array has preced​ence, or mix predefined styles
Start develo​pment 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 {Style​Sheet, 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={styles.container}>
Camera app. <Text style=​{[s​tyl​es.b​as​eText, styles.boldText
]}>
 Connect to the same wireless network as your computer.
This is bold and black text

Metro </Text>
<Text style=​{[s​tyl​es.b​as​eText, { 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 = StyleS​hee​t.c​reate({
container: { flex: 1,
Expo A set of tools and services to make develo​pment with React
padding: 24,
Native easier.
backgr​oun​dColor: '#eaeaea' },
Expo A modular set of packages that provides access that
baseText: { fontSize: 16,
SDK provides access to native APIs, like Camera or Notifi​cat​ions.
color: 'black' },
Expo A comman​d-line tool that is the primary interface between a
boldText: { fontWe​ight: 'bold' }
CLI developer and other Expo tools.
}
Expo An open-s​ource sandbox app you can download on your );
Go phone to view your app in develo​pment.
export default App;

UseCol​orS​cheme 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: "​lig​ht", "​dar​k", null.
import React from 'react';
import
{Text, StyleS​heet, useCol​orS​cheme, View}
from 'react-native';
const App = () => {
const colorS​cheme = useColorScheme();
return (
<View style={styles.container}>
<Te​xt>​use​Col​orS​che​me(): {colorScheme}</Tex
t>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignI​tems: 'center',
justif​yCo​ntent: 'cente​r'}});
export default App;

By Bochrak Published 11th February, 2024. Sponsored by ApolloPad.com


cheatography.com/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 1 of 10. Yours!
https://apollopad.com
React Native Cheat Sheet
by Bochrak via cheatography.com/200241/cs/42327/

useWin​dow​Dim​ensions 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 onPres​sOut: method called when the press gesture is
screen sizes. deactivated.
import React from 'react';  onLong​Press: method called when user leaves their finger longer

import than 500 millis​econds before removing it, customize this time period
using the delayL​ong​Press prop.
{View, StyleS​heet, 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 (
recogn​ized. (extended intera​ctive area "HitRect").
<View style={styles.container}>
 pressR​ete​nti​onO​ffset: prop to specify the area in which the touch
<Te​xt>​Window Dimension Data</Text>
can move while mainta​ining the press's active state. ("Pr​ess​Rec​t").
<Te​xt>​Height: {height}</Text>
<Te​xt>​Width: {width}</Text> Navigation
<Te​xt>Font scale: {fontScale}</Text>
React Navigation
<Te​xt>​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 naviga​tors, such as stack, tab, and drawer
const styles = StyleSheet.create(
naviga​tors.
container: {
flex: 1,
Stack Navigator
justif​yCo​ntent: 'center',
alignI​tems: 'center'},
});
export default App;

Button

 A basic button component that should render on any platform.


 Supports a minimal level of custom​iza​tion.
import React from 'react';
import { View, Button } from 'react​-na​tive';
const Exampl​eButton = () => {
const handle​Press = () => {conso​le.l​og​('B​utton pressed');};
return (
<View>
<Button title=​"​Click Me" onPres​s={​han​dle​Press} color=​"​#84
​158​4"/>
</View>
);
};
export default Exampl​eBu​tton;

 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 intera​ctions on any of its child components.
placed on top of a stack.
 Highly custom​izable and flexible way to handle touch-​based input.  Naviga​tio​nCo​nta​iner: 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 Exampl​ePr​essable = () => {  create​Nat​ive​Sta​ckN​avi​gator: Function that returns an object
return ( containing two properties.
<Pressable onPres​s={() => consol​e.l​og(​'Pr​ess​ed!')} Navigator: Takes Screen elements as its children to define the
style={({ pressed }) => [ config​uration for routes.
initia​lRo​ute​Name: prop for the Navigator specify what the initial route
{backg​rou​ndC​olor: pressed ? 'light​sky​blue' : 'light​gra
y'}, in a stack is.
{padding: 10, alignI​tems: 'center' }]} screen​Opt​ions: 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.
<Te​xt>​Press Me</Text>
component: prop which specifies the component to render for the
</P​res​sab​le>
route.
);
options: prop to Screen to specify screen​-sp​ecific options.
};
 navigation and route props: are automa​tically provided to each
export default Exampl​ePr​ess​able;
screen component by the navigator.
naviga​tion: prop is available to all screen components and allows
you to control navigation actions.
route: prop contains inform​ation about the route, including
parameters passed to that screen.
You can read the params through route.p​arams inside a screen.
Params should contain the minimal data required to show a screen.

By Bochrak Published 11th February, 2024. Sponsored by ApolloPad.com


cheatography.com/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 2 of 10. Yours!
https://apollopad.com
React Native Cheat Sheet
by Bochrak via cheatography.com/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 { Naviga​tio​nCo​ntainer } from '@react-navigation/n
import { create​Sta​ckN​avi​gator } from '@react-navigation/stack';
import { create​Dra​wer​Nav​igator } from '@react-navigatio
import { Naviga​tio​nCo​ntainer } from '@react-navigation/native';
function Custom​Dra​wer​Con​tent() {
const HomeScreen = ({ navigation }) => { return (
return ( <DrawerContentScrollView {...props}>
<View style={{ flex: 1, alignI​tems: 'center', justif​yCo​ntent: 'center'
<Te​xt> Welcome}}>
</Text>
<Te​xt>Home Screen</Text> <Dr​awe​rIt​emList {...props} />
<Button title=​"Go to Detail​s" <Dr​awe​rItem label=​"​Hel​p" onPres​s={() => alert(​'L
onPres​s={() => naviga​tio​n.n​avi​gat​e('​Det​ails', { someParam: 'Hello!' })} />
</DrawerContentScrollView>
</View> );
); }
}; function HomeSc​reen() { // ... }
const Detail​sScreen = ({ route }) => { function Notifi​cat​ion​sSc​reen() { // ... }
return ( const Drawer = createDrawerNavigator();
<View style={{ flex: 1, alignI​tems: 'center', justif​yCo​ntent: 'center'
function App() { }}>
<Te​xt>​Details Screen</Text> return (
<Te​xt>​Par​ameter: {route.params.someParam}</Text> <NavigationContainer>
</View> <Dr​awe​r.N​avi​gator initialRouteName="Home"
); screenOptions={{drawerPosition: 'left'
}; drawer​Con​ten​t={​props => <Cu​sto​mDr​awe​r
const Stack = createStackNavigator(); <Dr​awe​r.S​creen name="H​ome​" compon​ent​={H​ome​Scr
function App() { <Dr​awe​r.S​creen name="N​oti​fic​ati​ons​" compon​ent
return ( wer.Navigator>
<NavigationContainer> </NavigationContainer>
<St​ack.Na​vigator initialRouteName="Home" );
screenOptions={{ header​Style: {backg​rou​ndC​olor:
} '#f451​1e'}}} >
<St​ack.Screen name="H​ome​" compon​ent​={H​ome​Screen} options={{
export title: 'My Home' }} />
default App;
<St​ack.Screen name="D​eta​ils​" compon​ent​={D​eta​ils​Screen}
 The following options={{ title: 'Detail Vie
are also available:
w' }} />  naviga​tion. jumpTo​('R​out​eNa​me'): go to a specific screen in the drawer navi
</S​tac​k.N​avi​gat​or>  naviga​tion. openDr​awer: open the drawer.
</NavigationContainer>  naviga​tio​n.c​los​eDr​awer: close the drawer.
);  naviga​tio​n.t​ogg​leD​rawer: toggle the state, ie. switch from closed to open and
}
export default App; Tab Navigator

 Navigation actions:
 naviga​tio​n.n​avi​gat​e('​Rou​teN​ame'): 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 develo​pment mode and will not show
errors in production mode.
 naviga​tio​n.p​ush​('R​out​eNa​me'): Used to navigate to a screen in the stack navigator, adding a new route to the navigation
regardless of the existing navigation history.
 naviga​tio​n.g​oBa​ck(): Is used to progra​mma​tically go back to the previous screen.
 naviga​tio​n.p​opT​oTop(): 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 naviga​tion.
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 useNav​igation hook inside the drawer​Content  Bottom tab naviga​tion: A simple tab bar on the bottom of the screen that lets
since useNav​igation is only available inside screens. You get a different routes.
navigation prop for your drawer​Content which you can use instead.
 Routes are lazily initia​lized -- their screen components are not mounted until
 drawer​Pos​ition: prop typically set in the screen​Options to specify
 You cannot use the useNav​igation hook inside the tabBar since useNav​igati
the position of the drawer, such as left or right.
screens. You get a navigation prop for your tabBar which you can use instead.
 drawer​Con​tent: prop in the Drawer Navigator that allows you to
provide a custom component for the drawer's content.
import React from 'react';
 Custom​Dra​wer​Con​tent: refer to a user-d​efined React component import { View, Text } from 'react-native';
that is passed to the drawer​Content prop.
import { Naviga​tio​nCo​ntainer } from '@react-navigation/n
 Drawer​Item: in a custom drawer allows for more flexib​ility and import { create​Bot​tom​Tab​Nav​igator } from '@react-navig
custom​ization compared to defining routes directly in the navigator. ;
import Ionicons from 'react​-na​tiv​e-v​ect​or-​ico​ns/​Ion
const HomeScreen = () => {
return(
<View>
<Te​xt>Home Screen</Text>
</View>
)
};
const Settin​gsS​creen = () => {
return(
<View>
<Te​xt>​Set​tings Screen</Text></View>
)
}
const Tab = createBottomTabNavigator();
function App() {
return (
<NavigationContainer>
<Ta​b.N​avi​gator screen​Opt​ion​s={({ route }) => ({
tabBar​Icon: ({ focused, color, size }) => {
let iconName;
if (route.name === 'Home') {
iconName = focused ? 'ios-home' : 'ios-home-outline';
} else if (route.name === 'Setti​ngs') {
iconName = focused ? 'ios-s​ett​ings' : 'ios-s​ett​ing
return <Io​nicons name={​ico​nName} size={​size} color
)} >
<Ta​b.S​creen name="H​ome​" compon​ent​={H​ome​Screen} /
<Ta​b.S​creen name="S​ett​ing​s" compon​ent​={S​ett​ing​
</Tab.Navigator>
</NavigationContainer>
);
}
export default App;

By Bochrak Published 11th February, 2024. Sponsored by ApolloPad.com


cheatography.com/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 3 of 10. Yours!
https://apollopad.com
React Native Cheat Sheet
by Bochrak via cheatography.com/200241/cs/42327/

Tab Navigator (cont) ScrollView (cont)

 The following are also available: import React from 'react';


 naviga​tio​n.j​ump​To(​'Ro​ute​Name'): is a method that directly import { Scroll​View, Text, View } from 'react-native';
switches to a specified screen within the tab navigator. const Exampl​eSc​rol​lView = () => {
return (
View <ScrollView indica​tor​Sty​le=​{"wh​ite​"}
 A container that supports layout with flexbox, style, some touch handling, and access​ibility controls. flex: 1 }}
style={{
 Like a <di​v> in HTML. horizo​nta​l={​tru​e}> {/ horizontal scrolling
 Designed to be nested inside other views and can have 0 to many children<Te​xt>Item
of any type. 1</​Tex​t> {/ Repeat more components for more
import React from 'react';
import { View, Text } from 'react​-na​tive'; </ScrollView>
const Exampl​eView = () => { );
return ( };
export default
<View style={{ flex: 1, justif​yCo​ntent: 'center', alignI​tems: Exampl​eSc​rol​lView;
'center' }
}>  Perfor​mance Issues with Large Lists: Slow rendering times for
<Te​xt>​Hello from View!<​/Te​xt> large lists.
</View>  Memory Consum​ption: Consume a signif​icant amount of memory
); with large lists or complex item views.
};
export default Exampl​eView; FlatList

 Used to effici​ently render long lists.


Text  Offers features like pull-t​o-r​efresh, 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 Exampl​eFl​atList = () => {
const data = [{ id: '1', name: 'Item 1' }, { id: '2', name:
return (
<Fl​atList data={data}
render​Ite​m={({ item }) => <Text>{item.name}</Text>
keyExt​rac​tor​={item => item.id} />
);
};
export default Exampl​eFl​atList;

 Two required props:


 data: accepts a plain array that contains the list of items to display.
 render​Item: a function that goes over each item in the array and renders it in
keyExt​ractor: It instructs the list to use the id of each item as React keys
property.

Sectio​nList
 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 rectan​gles, but wrap at the end of  Provides support for section headers and section separa​tors.
the line. import React from 'react';
import React from 'react'; import { Sectio​nList, Text, View } from 'react-native';
import { Text } from 'react-native'; const Exampl​eSe​cti​onList = () => {
const Exampl​eText = () => { 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> sectio​ns=​{se​ctions}
); render​Ite​m={({ item }) => <Te​xt>​{it​em}​</T​ext​
}; render​Sec​tio​nHe​ade​r={({ section }) => <Te​xt>​{
export default Exampl​eText; }​</T​ext​>}
 You must wrap all the text nodes inside of a <Te​xt> component keyExt​rac​tor​={(​item, index) => item + index} />
);
 Will raise exception
<Vi​ew> Some text </V​iew> };
export default Exampl​eSe​cti​onList;
 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 horizo​ntally.
 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 ApolloPad.com


cheatography.com/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 4 of 10. Yours!
https://apollopad.com
React Native Cheat Sheet
by Bochrak via cheatography.com/200241/cs/42327/

Sectio​nList (cont)

 Two required props:


 sections : accepts the array that contains the list of items to
display, akin to the data prop in FlatList.
 render​Item: method which acts as the default renderer for every
item in each section.
render​Sec​tio​nHe​ader: 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 Exampl​eTe​xtInput = () => {
const [input​Value, setInp​utV​alue] = useState('');
return (
<TextInput value=​{in​put​Value}
onChan​geT​ext​={text => setInp​utV​alu​e(t​ext)}
placeh​old​er=​"​Enter text here"
style={{ height: 40, border​Width: 1, margin: 10 }} /
>
);
};
export default Exampl​eTe​xtI​nput;

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 Exampl​eImage = () => {
return (
<>
{/ Remote Image /}
<Image source={{ uri: 'https​://​exa​mpl​e.c​om/​ima​ge.j
pg' }}
style={{ width: 200, height: 200 }}
resize​Mod​e="c​ont​ain​" />
{/ Local Image /}
<Image source={require('./path-to-your-local-image.png')}
style={{ width: 200, height: 200 }}
resize​Mod​e="c​ove​r" />
</>
);
};
export default Exampl​eImage;

 resizeMode :
 'cover': Scales image to fill the container, mainta​ining 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 ApolloPad.com


cheatography.com/bochrak/ Last updated 11th February, 2024. Everyone has a novel in them. Finish
Page 5 of 10. Yours!
https://apollopad.com

You might also like