Categories
React Native

React Native — Toasts and Activity Indicator

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

ToastAndroid

We can show a toast in our Android app with the ToastAndroid component.

For instance, we can write:

import React from 'react';
import { View, StyleSheet, ToastAndroid, Button } from "react-native";
import Constants from "expo-constants";

const showToast = () => {
  ToastAndroid.show("Hello World", ToastAndroid.SHORT);
};

const showToastWithGravity = () => {
  ToastAndroid.showWithGravity(
    "Hello World",
    ToastAndroid.SHORT,
    ToastAndroid.CENTER
  );
};

const showToastWithGravityAndOffset = () => {
  ToastAndroid.showWithGravityAndOffset(
    "A wild toast appeared!",
    ToastAndroid.LONG,
    ToastAndroid.BOTTOM,
    25,
    50
  );
};

export default function App() {
  return (
    <View style={styles.container}>
      <Button title="Toggle Toast" onPress={() => showToast()} />
      <Button
        title="Toggle Toast With Gravity"
        onPress={() => showToastWithGravity()}
      />
      <Button
        title="Toggle Toast With Gravity & Offset"
        onPress={() => showToastWithGravityAndOffset()}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8
  },
});

We call the ToastAndroid.show method to show a simple toast.

ToastAndroid.showWithGravity shows the toast with gravity.

ToastAndroid.showWithGravity shows a toast with gravity and position offset.

Also, we can show a toast by setting the visibility state manually.

For example, we can write:

import React, { useEffect, useState } from 'react';
import { View, StyleSheet, ToastAndroid, Button } from "react-native";
import Constants from "expo-constants";

const Toast = ({ visible, message }) => {
  if (visible) {
    ToastAndroid.showWithGravityAndOffset(
      message,
      ToastAndroid.LONG,
      ToastAndroid.BOTTOM,
      25,
      50
    );
    return null;
  }
  return null;
};

export default function App() {
  const [visibleToast, setvisibleToast] = useState(false);

  useEffect(() => setvisibleToast(false), [visibleToast]);

  const handleButtonPress = () => {
    setvisibleToast(true);
  };

  return (
    <View style={styles.container}>
      <Toast visible={visibleToast} message="Example" />
      <Button title="Toggle Toast" onPress={() => handleButtonPress()} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8
  },
});

We created our own Toast component with the visible prop to control the toast’s visibility.

Also, we pass the message into the toast with the message prop.

When the visibleToast state changes, we make it invisible first with the useEffect callback and then make it visible again.

ActivityIndicator

We can add an activity indicator in our app with the ActivityIndicator component.

For example, we can write:

import React from 'react';
import { ActivityIndicator, StyleSheet, Text, View } from "react-native";
export default function App() {
  return (
    <View style={[styles.container, styles.horizontal]}>
      <ActivityIndicator />
      <ActivityIndicator size="large" />
      <ActivityIndicator size="small" color="green" />
      <ActivityIndicator size="large" color="blue" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center"
  },
  horizontal: {
    flexDirection: "row",
    justifyContent: "space-around",
    padding: 10
  }
});

We add the ActivityIndicator component to show it.

The size prop controls the size and the color changes the color.

Conclusion

We can add an activity indicator and toasts with React Native.

Categories
React Native

React Native — Section List and Back Button Handling

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

SectionList

We can add the SectionList component to display a section list view.

It’s cross-platform and works with horizontal mode.

Also, it has header, footer, and separator support.

We can pull it to refresh the data.

We can load data as we scroll with it.

And it also has multiple columns support.

For example, we can write:

import React from 'react';
import { SafeAreaView, StyleSheet, Text, View, SectionList } from 'react-native';
const DATA = [
  {
    title: "Main dishes",
    data: ["Pizza", "Burger", "Risotto"]
  },
  {
    title: "Sides",
    data: ["French Fries", "Onion Rings", "Fried Shrimps"]
  },
  {
    title: "Drinks",
    data: ["Water", "Coke", "Beer"]
  },
  {
    title: "Desserts",
    data: ["Cheese Cake", "Ice Cream"]
  }
];
const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);
export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <SectionList
        sections={DATA}
        keyExtractor={(item, index) => item + index}
        renderItem={({ item }) => <Item title={item} />}
        renderSectionHeader={({ section: { title } }) => (
          <Text style={styles.header}>{title}</Text>
        )}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 0
  },
  item: {
    backgroundColor: 'pink',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

We add the SafeAreaView and the SectionList to display a list with section headings and each section having their own content.

The sections prop has the data.

keyExtractor is a function that returns the unique index for the item.

renderItem is a function that renders the item.

The renderSectionHeader prop renders the header with a function.

BackHandler

We can use the BackHandler API to handle back button presses.

For instance, we can write:

import React, { useEffect } from 'react';
import { Text, View, StyleSheet, BackHandler, Alert } from "react-native";

export default function App() {
  useEffect(() => {
    const backAction = () => {
      Alert.alert("Are you sure?", "Are you sure you want to go back?", [
        {
          text: "Cancel",
          onPress: () => null,
          style: "cancel"
        },
        { text: "YES", onPress: () => BackHandler.exitApp() }
      ]);
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      backAction
    );

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

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Click Back button!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    fontSize: 18,
    fontWeight: "bold"
  }
});

We attach an event handler for the hardwareBackPress event with BackHandler.addEventListener .

In the backAction event handler function, we show an alert with the Alert.alert method.

It takes the title and the content for the alert as the argument.

The 3rd argument is an array with the objects having the content of the cancel button.

The text property is the text for the button.

onPress is a function that runs when we press the button.

style has the style for the button.

When the component unmounts, we call backHandler.remove() to remove the hardwareBackPress listener.

Conclusion

We can add the SectionList component to add a list with section headings and list items for each section.

Also, we can add a handler for the back button.

Categories
React Native

React Native — Drawer and Permissions

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

DrawerLayoutAndroid

We can add a drawer layout to our Android app with the DrawerLayoutAndroid component.

For instance, we can write:

import React, { useState } from 'react';
import { Button, DrawerLayoutAndroid, Text, StyleSheet, View } from "react-native";

export default function App() {
  const [drawerPosition, setDrawerPosition] = useState("left");
  const changeDrawerPosition = () => {
    if (drawerPosition === "left") {
      setDrawerPosition("right");
    } else {
      setDrawerPosition("left");
    }
  };

  const navigationView = (
    <View style={styles.navigationContainer}>
      <Text style={{ margin: 10, fontSize: 15 }}>I'm in the Drawer!</Text>
    </View>
  );

  return (
    <DrawerLayoutAndroid
      drawerWidth={300}
      drawerPosition={drawerPosition}
      renderNavigationView={() => navigationView}
    >
      <View style={styles.container}>
        <Text style={{ margin: 10, fontSize: 15 }}>
          DrawerLayoutAndroid example
        </Text>
        <Button
          title="Change Drawer Position"
          onPress={() => changeDrawerPosition()}
        />
        <Text style={{ margin: 10, fontSize: 15 }}>
          Drawer on the {drawerPosition}! Swipe from the side to see!
        </Text>
      </View>
    </DrawerLayoutAndroid>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    paddingTop: 50,
    backgroundColor: "#ecf0f1",
    padding: 8
  },
  navigationContainer: {
    flex: 1,
    paddingTop: 50,
    backgroundColor: "#fff",
    padding: 8
  }
});

We have the drawerPosition state to change the drawer’s position.

The Button takes the onPress prop that takes a function that calls the changeDrawerPosition to toggle the position of the drawer.

The DrawerLayoutAndroid component has the drawer.

drawerWidth has the drawer’s width.

drawerPosition sets the drawer’s position.

renderNavigationView is a function that renders the drawer’s content.

Then when we drag left or right, we’ll see the drawer.

PermissionsAndroid

We can add the PermissionsAndroid object to let us request permissions in our app.

For example, we can write:

import React from 'react';
import { StyleSheet, Text, View, PermissionsAndroid, Button } from "react-native";
import Constants from "expo-constants";

const requestCameraPermission = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA,
      {
        title: "Camera Permission",
        message:
          "Can I use the Camera?",
        buttonNeutral: "Ask Me Later",
        buttonNegative: "Cancel",
        buttonPositive: "OK"
      }
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can use the camera");
    } else {
      console.log("Camera permission denied");
    }
  } catch (err) {
    console.warn(err);
  }
};
export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.item}>Try permissions</Text>
      <Button title="request permissions" onPress={requestCameraPermission} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8
  },
  item: {
    margin: 24,
    fontSize: 28,
    fontWeight: "bold",
    textAlign: "center"
  }
});

We add the requestCameraPermission function that calls the PermissionAndroid.request method to request permission.

The PermissionsAndroid.PERMISSIONS.CAMERA argument means we want to get permissions for the camera.

The 2nd argument has an object with some properties.

title is the title for the permission request dialog.

message is the message for the permission request dialog.

buttonNeutral is the text that’s shown for the neutral choice.

buttonNegative is the text for the button for denying permission.

buttonPosition is the text for the button for accepting permission.

It returns a promise with the permission choice.

We can check if it’s granted by checking against PermissionsAndroid.RESULTS.GRANTED .

Conclusion

We can add a drawer and request permissions with the React Native library.

Categories
React Native

React Native — ScrollViews, Style Sheets, and Switches

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

ScrollView

The ScrollView lets us display a scrollable container in our React Native app.

For example, we can use it by writing:

import React from 'react';
import { SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <ScrollView style={styles.scrollView}>
        <Text style={styles.text}>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi.
        </Text>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: Constants.statusBarHeight,
  },
  scrollView: {
    backgroundColor: 'pink',
    marginHorizontal: 20,
  },
  text: {
    fontSize: 100,
  },
});

We add the ScrollView inside the SafeAreaView to enable scrolling.

Inside the ScrollView , we have text that overflows the screen vertically, so we can scroll through it because of the ScrollView .

StyleSheet

We can create styles that we can apply to our components with the StyleSheet.create method.

For example, we can write:

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

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>React Native</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 24,
    backgroundColor: "#eaeaea"
  },
  title: {
    marginTop: 16,
    paddingVertical: 8,
    borderWidth: 4,
    borderColor: "black",
    borderRadius: 6,
    backgroundColor: "lightgreen",
    color: "black",
    textAlign: "center",
    fontSize: 30,
    fontWeight: "bold"
  }
});

We create the container and title properties in the styles object.

Like React, we just create styles with CSS properties and values.

Switch

We can use the Switch component to render a boolean input.

For example, we can write:

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

export default function App() {
  const [isEnabled, setIsEnabled] = React.useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);
  return (
    <View style={styles.container}>
      <Switch
        trackColor={{ false: "red", true: "green" }}
        thumbColor={isEnabled ? "green" : "red"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
    </View>
  );
}

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

We add the Switch component to add a toggle switch into our app.

The trackColor is the color of the switch button background.

The false color is displayed when the toggle is false.

The true color is displayed when the toggle is true.

thumbColor is the color of the switch button itself.

ios_backgroundColor is the background color of the switch when it’s in an iOS app.

onValueChange has a function that gets the value of the switch and does something with it.

In our code, we use the useState hook to set the isEnabled state.

Conclusion

We can add a scroll view component to let us scroll through overflowing content.

Also, we can style our app with the StyleSheet object.

The Switch component lets us add a toggle switch.

Categories
React Native

React Native — Nested Text and Text Input

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

Nested Text

We can add nested Text components.

For instance, we can write:

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

export default function App() {
  return (
    <View
      style={{
        flexDirection: "row",
        height: 100,
        padding: 20
      }}
    >
      <Text style={styles.baseText}>
        I am bold
      <Text style={styles.innerText}> and red</Text>
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  baseText: {
    fontWeight: 'bold'
  },
  innerText: {
    color: 'red'
  }
});

We add the Text component within another Text component.

Then we styled them with the styles created with the StyleSheet.create method.

Containers

Everything inside the Text element isn’t using flexbox layout.

They’re using text layout.

For example, if we have:

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

export default function App() {
  return (
    <Text>
      <Text>First part and </Text>
      <Text>second part</Text>
    </Text>
  );
}

then we see everything inline.

If we have:

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

export default function App() {
  return (
    <View>
      <Text>First part and </Text>
      <Text>second part</Text>
    </View>
  );
}

then we see:

First part and
second part

Text must be wrapped in a Text component.

The Text component lets us inherit styles.

For example, if we have:

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

export default function App() {
  return (
    <View>
      <Text style={{ fontWeight: 'bold' }}>
        I am bold
        <Text style={{ color: 'red' }}>and red</Text>
      </Text>
    </View>
  );
}

Then we have all the text inside the outer Text component being bold.

And the ‘and red’ text is red and bold.

TextInput

We can add text input into our app with the TextInput component.

For example, we can write:

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

export default function App() {
  const [value, onChangeText] = React.useState('hello world');

  return (
    <View>
      <TextInput
        style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
        onChangeText={text => onChangeText(text)}
        value={value}
      />
      <Text>{value}</Text>
    </View>
  );
}

to add an text input with the TextInput component.

We listen to input value changes by passing in a function to the onChangeText prop.

Then the value ‘s value will have the latest inputted text.

We can the max number of characters in the input with the maxLength prop:

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

export default function App() {
  const [value, onChangeText] = React.useState('hello world');

  return (
    <View>
      <TextInput
        style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
        onChangeText={text => onChangeText(text)}
        value={value}
        editable
        maxLength={40}
      />
      <Text>{value}</Text>
    </View>
  );
}

Now we can only enter 40 characters into the input max.

Conclusion

We can add nested Text components.

Also, we can add text inputs with the TextInput component.