React Native – Introduction

React Native is an open-source UI framework used to develop mobile applications. It provides the capability to use the React framework along with native platform capabilities. React Native can be used for building both iOS and Android apps. However if you directly have to talk to the native APIs you will have to go with Java/Kotlin for Android and Swift/Objective C for iOS. But that’s often not the case.

React Native is a collection of react components to build a user interface for a mobile app. React Native views which are written in react + react native are finally compiled to real native App.

React Native compiles reusable components like <View> to actual (android/iOS) native components (<View> to android.view for Android or UIView for iOS). Other business logic written in Javascript is run as a Javascript thread on a special virtual machine inside the native app.

There are two ways of building React Native applications. Either using

  • React Native CLI or
  • Expo CLI (build on top of React Native CLI)

Expo is like a thin wrapper around React native CLI. It provides a lot of utility features and simplifies the setup process. Expo is really easy and quite ideal for beginners. You can always switch to React Native CLI anytime to use the Native-only features.

React Native keeps pushing new updates every month, hence the apps in production might need a re-visit often but not every month. Also, the developer needs to keep track of major updates to Expo and other 3rd party libraries used.

Installation and Setup:

npm install -g expo-cli
expo init <AppName>
npm start

Open Metro Bundler: http://localhost:19002/

The Metro Bundler has the option to run in web browser, which is the simplest option:

  • the run in web browser: opens up a new browser where you can see the application.
  • To Use Android emulator:

Android Emulator:

  • Install Android Studio
  • Use the recommended(standard) installation settings
  • Go to Tools > AVD (Android Virtual Device) Manager
  • Select a preferred device model and the latest android version and install. Preferably the one with Google Playstore.
  • Select a system image: Go with the second one – which is mostly the latest
  • Click on Launch AVD under ‘Actions’
  • You should now see the virtual device launched on your system.
  • Go to Metro Bundler and select “Run on android device/ emulator” or press “a” on the terminal – It will download Expo on the virtual device and run the app.
  • You can press ctrl+m to get the menu options for expo.
  • Every time you make code changes and save it, the app will be auto-reloaded and display the current changes

To run on a physical device:

  • Install Expo on the physical device from PlayStore.
  • Scan the code given in the Metro Bundler.
  • That’s it! Now your app should be up and running. It might take longer for the first time but hot reloads should be very quick eventually.

Tip: To Auto format code on save in VS Code: File > Preferences > settings > search for ” format on save” and select the option

React Native – Basics

React Native has built in components which are the only ones that can be used to build apps. We can build custom components using these basic components as building blocks. Ex. <Text>,<View>,<Button> etc. You can also nest components into one another.

Styling – there is no CSS in React Native. However, it provides the StyleSheet Object for styling the app. They look very much like CSS. This is the preferred way. You can also use Inline styling

Flexbox helps in layout ( ex. to place elements next to each other.)

  • JustifyContent -> for the main axis, AlignContent -> cross axis.
  • flex is a property inside flexbox. i.e. the parent component contains the flexbox property and the child component uses the flex property to set the layout.
  • Stylesheet.create() has potential to optimize performance in the future. Hence it is always recommended to use this object. Moreover, it can detect incorrect style property or value. Also makes it reusable.

Note: to format Document in VS code: File > preferences > keyboard shortcuts > format document (shift+alt+f for windows)

Styling:

React Native styling is inspired by CSS but css doesn’t work here as such. They do look much like CSS. Styling translations are provided and they are the only ones that react widgets understand. React Native does the heavy lifting in the background.

Inline Styling

<View
        style={{
          backgroundColor: 'blue',
          width: 100,
          height: 100,
          justifyContent: 'center',
          alignItems: 'center'
        }}
      ></View>

Stylesheet Object

const styles = StyleSheet.create({
  inputContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },

Working with State

React Native uses React Hooks for handling the State.

export default function App() {
  const [outputText, setOutputText ] = useState('Hello React Native!')
  ...

Scrolling items

Scrolling can be achieved by wrapping the view in <ScrollView> – Ideal for a short list of 10-20 items. Example:

<ScrollView>
        {goalsList.map((goal) => (
          <View key={goal} style={styles.goalList}>
            <Text>{goal}</Text>
          </View>
        ))}
</ScrollView>

FlatList

FlatList is used for better performance. FlatList optimizes scrolling by only rendering as much as required on the screen view. The data should be in the form of key, value pairs

const addGoalHandler = () => {
    setGoalsList((currentGoals) => [
      ...currentGoals,
      { key: Math.random.toString(), value: enteredGoal },
    ]);
  };

<FlatList
        data={goalsList}
        renderItem={(itemData) => (
          <View style={styles.goalList}>
            <Text>{itemData.item.value}</Text>
          </View>
        )}
      />

Creating custom components

Create a new folder, ideally named as components (can be named anything else). It is a convention to start the name of the component with a capital letter.

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

const GoalItem = (props) => {
  return (
    <View style={styles.goalList}>
      <Text>{props.title}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  goalList: {
    padding: 10,
    marginVertical: 10,
    backgroundColor: "#ccc",
    borderColor: "black",
    borderWidth: 1,
  },
});

Touchable components

React Native offers the following components for creating a touchable component.

  • <Touchable> only wraps the components
  • <TouchableOpacity> can have events and adds an effect of making the wrapped component opaque on touch
  • <TouchableHighlight> – changes the background on touch, giving a highlighted look.

To create a modal that are positioned over the main component, The <View> should be wrapped with a <Modal> component. It provides a lot of properties like visibility, animation etc.

<Modal visible={props.visible} animationType="slide">
      <View style={styles.inputContainer}>
        <TextInput
          placeholder="Life Goals"
          style={styles.inputGoal}
          onChangeText={enteredGoalHandler}
          value={enteredGoal}
        />
        <Button title="ADD" onPress={props.onAddGoal.bind(this, enteredGoal)} />
      </View>
</Modal>
const styles = StyleSheet.create({
 
  inputContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

flex value 1 – lets the modal take as much space as the component allows. Not setting flex will make the modal take only as much space as the component needs.

Debugging

A few ways of debugging your React Native App:

  • Reading error message – Can be very informative and can sometimes give the right fix
  • console.log() – in order to understand the code flow
  • Chrome Debugger: On Android Simulator:
    • (ctrl+m for Android cmd+d for iOS)
    • option: Debug Remote JS
    • ctrl+shift+j opens the debugger console
    • option: performance monitor – helps to see how the app is behaving, spotting memory leaks
    • option: show element inspector – can show how each component is placed on screen with respect to the code.
  • Downloading React Native Debugger from the github page: https://github.com/jhen0409/react-native-debugger/releases

Author: Shilpa

https://kriyavikalpa.com/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s