React Native cheatsheet for beginners

React native is one of the most demanding cross platform frameworks developed by Meta (Facebook) for creating mobile applications with ease. It follows Learn Once, Write Anywhere paradigm which allows users to create components using Javascript, HTML5 …


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Vishnu Sivan

React native is one of the most demanding cross platform frameworks developed by Meta (Facebook) for creating mobile applications with ease. It follows Learn Once, Write Anywhere paradigm which allows users to create components using Javascript, HTML5 and CSS files.

React Native redefines the functionality of native apps, which were earlier inefficient and slow to deploy. It creates hybrid apps along with native functionality. It is based on React.js UI library which makes it easy to switch between web developers and mobile app developers.

In this article, we provide a small cheat sheet for react native developers to make the development process handy.

Getting Started

Table of contents

  • Creating an app
  • Running the app
  • Upgrading React Native
  • Code snippets
  • Components
  • State and props
  • useState and useEffect
  • Core Components
  • View
  • ScrollView
  • Text
  • Image
  • Button
  • TouchableHighlight / TouchableOpacity
  • TextInput
  • FlatList
  • Stylesheet
  • Inline Styling
  • Flexbox
  • Detecting Screen Size
  • Navigation
  • useNavigation Hook
  • BackHandler android
  • Networking
  • Creating a sample app
  • React Native Cheatsheet Let’s have a look at some of the key points of react native.

Creating an app

To create a new mobile app, open the terminal and execute the following commands,

npx react-native init AppName
//or
npx create-react-native-app AppName

Running the app

To run the app, open the terminal and execute the following commands,

cd AppName
npx react-native run-android
//or
npx react-native run-android

Upgrading React Native

To upgrade react native to the latest version, open the terminal and execute the following commands,

npm install react-native@latest;

Code snippets

Let’s go through some code snippets which are commonly used in react native projects.

Components

Components are light weight modules, considered as core building blocks of React and React-Native apps. The App component is the default component which binds with the virtual dom in react native. Each component in react native has the following structure (It is optional to provide View and Text 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 whole 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 hook allows 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

Core components are ready to use components available in React Native, which includes ,, ,, FlatList,, and .

View

The <View> component act as a container and can be translated as <div> from web.

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

Similar to View, it is a generic container with scrolling support to provide responsive layout for different devices.

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

The <Text> component is used to display text in React Native.

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

Image

The <Image> component is used to render images in react native. It accepts images from remote and local sources.

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

The <Button> component is a touchable element used to interact with the screen and to perform operations.

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

TouchableHighlight / TouchableOpacity

The <TouchableHighlight> / <TouchableOpacity> component is a wrapper for making views respond in accordance to touches. On press down, the opacity of the wrapped view is decreased, which allows the underlay color to show through. It must have at least one child component.

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

The <TextInput> component allows user to enter text into the app. It has an onChangeText event which is called every time the text changes.

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

The <FlatList> component displays a scrolling list of items. It renders only those elements that are currently shown on the screen.

The FlatList component requires two props: data and renderItem. data is the source of the list and renderItem returns a formatted component to render.

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

The <StyleSheet> is an abstraction that replaces CSS by accepting CSS styling rules using a two-dimensional JavaScript object.

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

React native allows users to add style within the HTML element using double curly brackets ({{}}).

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

Flexbox

The <Flexbox> component is used to layout the component’s children.

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

Detecting the screen size of the device is essential to alter the layout, text sizes, and other aspects of the app.

import { Dimensions } from 'react-native';

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

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

Navigation

React Navigation’s native stack navigator provides a way for your app to transition between screens and manage navigation history.

In the react-navigation library, all navigator methods follow a naming pattern like create<type>Navigator(), which returns an object with Navigator and Screen properties.

createNativeStackNavigator is a function that returns an object containing 2 properties: Screen and Navigator.
NavigationContainer 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

Usage
In the below code, a home screen component is created and binded with the stack navigator.

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;

useNavigation Hook

The useNavigation hook provides access to the navigation API and can be used to implement transition from one screen to another.

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

In order to handle the back button actions from the code, the BackHandler API helps to detect hardware button presses for back navigation, and registers event listeners for the system’s back action.

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

Most of the mobile apps require to load resources from a remote URL. React Native provides the Fetch API for fetching data from remote sources.

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;

Creating a sample app

Let’s try to create a profile component to get in touch with the react native components and other functionalities.

  • 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.
        {'\n\n'}
        <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 the following command
npx react-native run-android

You can see the following page after the successful run

demo

There you have it! Your own profile app using React native :)

React Native Cheatsheet

cheatsheet

Thanks for reading this article.

Thanks Gowri M Bhatt for reviewing the content.

If you enjoyed this article, please click on the heart button ♥ and share to help others find it!

The full source code for this tutorial can be found here,

GitHub - codemaker2015/react-native-cheatsheet

The article is also available on Medium.

Here are some useful links,


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Vishnu Sivan


Print Share Comment Cite Upload Translate Updates
APA

Vishnu Sivan | Sciencx (2022-12-17T17:34:18+00:00) React Native cheatsheet for beginners. Retrieved from https://www.scien.cx/2022/12/17/react-native-cheatsheet-for-beginners/

MLA
" » React Native cheatsheet for beginners." Vishnu Sivan | Sciencx - Saturday December 17, 2022, https://www.scien.cx/2022/12/17/react-native-cheatsheet-for-beginners/
HARVARD
Vishnu Sivan | Sciencx Saturday December 17, 2022 » React Native cheatsheet for beginners., viewed ,<https://www.scien.cx/2022/12/17/react-native-cheatsheet-for-beginners/>
VANCOUVER
Vishnu Sivan | Sciencx - » React Native cheatsheet for beginners. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/12/17/react-native-cheatsheet-for-beginners/
CHICAGO
" » React Native cheatsheet for beginners." Vishnu Sivan | Sciencx - Accessed . https://www.scien.cx/2022/12/17/react-native-cheatsheet-for-beginners/
IEEE
" » React Native cheatsheet for beginners." Vishnu Sivan | Sciencx [Online]. Available: https://www.scien.cx/2022/12/17/react-native-cheatsheet-for-beginners/. [Accessed: ]
rf:citation
» React Native cheatsheet for beginners | Vishnu Sivan | Sciencx | https://www.scien.cx/2022/12/17/react-native-cheatsheet-for-beginners/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.