You are currently viewing React Native cheatsheet for beginners |  by Vishnu Sivan |  Coinmonks |  Dec, 2022

React Native cheatsheet for beginners | by Vishnu Sivan | Coinmonks | Dec, 2022

Copy trading bots from the top traders. Try it for FREE.

Table of contents

Creating an app

npx react-native init AppName

//or

npx create-react-native-app AppName

Running the app

cd AppName
npx react-native run-android

//or

npx react-native run-android

Upgrading React Native

npm install react-native@latest;

Code snippets

Components

import * as React from 'react';
import {View, Text, StyleSheet} from 'react-native'

const App = () => {
return (
<View style={styles.container}>
<Text>Hello World</Text>
</View>
)
}

const styles = StyleSheet.create({
container: {
flex: 1,
},
});

export default App;

State and props

  • State is a mutable store that holds the entire state tree of the application.
  • Props is an immutable react native object set by the parent, and they are fixed throughout the lifetime of a component.
import { useState } from "react";
import {
StyleSheet,
Text,
View
} from 'react-native';

export default App = (props) => {
const [count, setCount] = useState(0);

return (
<View >
<Text style={styles.header}>
{props.title?.toUpperCase()}
</Text>
<Text>Count: {count}</Text>
</View>
);
}

App.defaultProps = {
title: 'Hello React Native'
}

const styles = StyleSheet.create({
header: {
fontFamily: 'Roboto',
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
},
});

useState and useEffect

  • The useState hook allows to track state in a function component.
  • The useEffect The hook allows the user to perform side effects such as fetching data, directly updating the DOM, and timers in the application.
import { useState, useEffect } from "react";

function App() {
const [count, setCount] = useState(0);

useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});

return <h1>Count: {count}</h1>;
}

Core Components

View

function App() {
return (
{/* Base layout structure */}
<View style={{ flex: 1 }}>
{/* Simple background color */}
<View style={{ padding: 10, color: 'blue' }}>
<Text>Text with background color</Text>
</View>
{/* Space layout structure */}
<View style={{ margin: 10 }} />
</View>
);
}

scrollView

function App() {
return (
<ScrollView>
<Text style={{ margin: 10 }}>Hello World</Text>
<View style={{ marginTop: 512 }} />
<Text style={{ margin: 10 }}>Welcome to React Native</Text>
</ScrollView>
);
}

Text

function App() {
return (
<Text style={{ height: 20, margin: 10 }}>
Hello World
</Text>
);
}

Image

function App() {
return (
<>
<Image source={require('./assets/logo.jpg')} />
<Image source={{ uri: 'https://github.com/codemaker2015/codemaker2015/raw/main/codemaker.png' }} />
<Image source={{ uri: 'data:image/png;base64,<base64-string>=' }} />
</>
);
}

Button

function App() {
return (
<Button
onPress={onPressSubmit}
title="Submit"
color="#FFFFFF"
/>
);
}

TouchableHighlight / TouchableOpacity

import React, {useState} from 'react';
import {Text, TouchableHighlight, TouchableOpacity, View} from 'react-native';

const App = () => {
const [count, setCount] = useState(0);
const onIncrement = () => setCount(count + 1);
const onDecrement = () => setCount(count - 1);

return (
<View
style={{
flex: 1,
margin: 20,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>Count: {count}</Text>
<TouchableOpacity
onPress={onIncrement}
style={{backgroundColor: '#F3F3F3', margin: 20, padding: 20}}>
<Text>+</Text>
</TouchableOpacity>
<TouchableHighlight
onPress={onDecrement}
style={{backgroundColor: '#F3F3F3', margin: 20, padding: 20}}>
<Text>-</Text>
</TouchableHighlight>
</View>
);
};

export default App;

TextInput

import React, {useState} from 'react';
import {Text, TextInput, View} from 'react-native';

const App = () => {
const [text, setText] = useState('');
return (
<View style={{padding: 15}}>
<TextInput
style={{height: 50}}
placeholder="Enter name"
onChangeText={name => setText(name)}
defaultValue={text}
/>
<Text style={{padding: 10, fontSize: 30}}>{text}</Text>
</View>
);
};

export default App;

FlatList

import React from 'react';
import {FlatList, Text, View} from 'react-native';

const App = () => {
return (
<View>
<FlatList
data={[
{key: 'January'},
{key: 'February'},
{key: 'March'},
{key: 'April'},
]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
</View>
);
};

stylesheet

function App() {
return (
<>
<Text style={styles.heading}>React Native</Text>
<Text style={styles.message}>Hello World</Text>
</>
);
}

const styles = StyleSheet.create({
heading: {
fontSize: 16,
},
message: {
fontSize: 11,
textTransform: 'uppercase',
},
});

Inline Styling

function App() {
const [color, setColor] = useState("red");
return (
<View>
<Text style={{"border":`1px solid ${color}`}}>Color: {color}</Text>
</View>
);
}

Flexbox

import { View, Text, StyleSheet } from "react-native";

const App = () => {
return (
<View style={[styles.container, {
// Try setting `flexDirection` to `"column"`.
flexDirection: "column"
}]}>
<View style={{ flex: 1, backgroundColor: "red" }} />
<View style={{ flex: 2, backgroundColor: "orange" }} />
<View style={{ flex: 3, backgroundColor: "green" }} />
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
}
});

export default App;

Detecting Screen Size

import { Dimensions } from 'react-native';

const { width, height } = Dimensions.get('window');

alert(Screen size: ${width}x${height});

Navigation

  • createNativeStackNavigator is a function that returns an object containing 2 properties: Screen and Navigator.
  • NavigationContainer It is a component which manages the navigation tree and contains the navigation state.
  • To install the library, execute the following code.
npm install @react-navigation/native-stack
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}

const Stack = createNativeStackNavigator();

function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}

export default App;

useNavigationHook

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function App() {
const navigation = useNavigation();

return (
<Button
title="Back"
onPress={() => {
navigation.goBack();
}}
/>
);
}
export default App;

BackHandler android

import {useEffect} from 'react';
import {BackHandler} from 'react-native';

function App() {
useEffect(() => {
const backAction = () => {
console.log("back button pressed");
return false; // back button is enabled
return true; // back button is disabled
};

// Register for hardware back event and attach a handler to it
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
backAction,
);

return () => backHandler.remove();
}, []);
};

export default App;

Networking

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';

function App() {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);

const getMovies = async () => {
try {
const response = await fetch('https://reactnative.dev/movies.json');
const json = await response.json();
setData(json.movies);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}

useEffect(() => {
getMovies();
}, []);

return (
<View style={{ flex: 1, padding: 20 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.title}, {item.releaseYear}</Text>
)}
/>
)}
</View>
);
}
export default App;

  • Create a new react native project using the following command
npx react-native init MyProfileApp
  • open App.js file and add the following code to it.
import React, {useState, useEffect} from 'react';
import {
Button,
Image,
StyleSheet,
Text,
View,
ScrollView,
Linking,
Dimensions,
ActivityIndicator,
} from 'react-native';

const {width, height} = Dimensions.get('window');

function Link(props) {
return (
<Text
{...props}
accessibilityRole="link"
style={StyleSheet.compose(styles.link, props.style)}
/>
);
}

function App() {
const [logoUri, setLogoUri] = useState(
'https://avatars.githubusercontent.com/',
);
const [loading, setLoading] = useState(false);

const getLogoUri = async () => {
try {
setLoading(true);
const response = await fetch(
'https://api.github.com/users/codemaker2015',
);
const json = await response.json();
setLogoUri(json?.avatar_url);
setLoading(false);
} catch (error) {
console.error(error);
setLoading(false);
}
};

useEffect(() => {
console.log('component is mounted');
getLogoUri();
return () => {
console.log('component is unmounted');
};
}, []);

return (
<ScrollView contentContainerStyle={styles.app}>
<View style={styles.header}>
{loading ? (
<ActivityIndicator />
) : (
<Image
accessibilityLabel="React logo"
source={{uri: logoUri}}
resizeMode="contain"
style={styles.logo}
/>
)}
<Text style={styles.title}>Vishnu Sivan</Text>
</View>
<Text style={styles.subTitle}>Immersive tech lead, TCS RapidLabs</Text>
<Text style={styles.text}>
Seasoned professional, forward looking software engineer with 3+ years
of experience in creating and executing innovative solutions in
immersive field to enhance business productivity.
{'nn'}
<Link
href="https://github.com/necolas/react-native-web"
onPress={() => {
Linking.openURL('https://github.com/codemaker2015');
}}>
Know more about me
</Link>
</Text>
<Button
onPress={() => {
Linking.openURL('mailto:codemaker2015@gmail.com');
}}
title="Contact Me"
/>
</ScrollView>
);
}

const styles = StyleSheet.create({
app: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F3F3F3',
width: width,
height: height,
},
logo: {
width: 180,
height: 180,
borderRadius: 10,
},
header: {
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: 10,
},
title: {
fontWeight: 'bold',
fontSize: 30,
marginVertical: 10,
textAlign: 'center',
},
subTitle: {
fontWeight: 'bold',
fontSize: 20,
marginVertical: 10,
textAlign: 'center',
},
text: {
lineHeight: 20,
fontSize: 18,
margin: 18,
textAlign: 'center',
},
link: {
color: '#1B95E0',
},
});
export default App;

  • Run the app by executing thefollowing command
npx react-native run-android

Join Coinmonks Telegram Channel and YouTube Channel Learn about crypto trading and investing

Leave a Reply