Categories
JavaScript Answers React Native

How to add a floating action button on React Native

Sometimes, we want to add a floating action button on React Native.

In this article, we’ll look at how to add a floating action button on React Native.

How to add a floating action button on React Native

To add a floating action button on React Native, we can use the TouchableOpacity and Icon components.

For instance, we write:

import * as React from 'react';
import { TouchableOpacity, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
import { Icon } from 'react-native-elements';

export default function App() {
  return (
    <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}>
      <TouchableOpacity
        style={{
          borderWidth: 1,
          borderColor: 'rgba(0,0,0,0.2)',
          alignItems: 'center',
          justifyContent: 'center',
          width: 70,
          position: 'absolute',
          bottom: 10,
          right: 10,
          height: 70,
          backgroundColor: '#fff',
          borderRadius: 100,
        }}>
        <Icon name="plus" size={30} color="#01a699" />
      </TouchableOpacity>
    </View>
  );
}

to position that TouchableOpacity component with position, bottom, and right properties.

We set borderRadius to 100 to make it round.

And we set justifyContent and alignItems to 'center' to center the contents.

Next, we add an Icon in it to show an icon inside the button.

Conclusion

To add a floating action button on React Native, we can use the TouchableOpacity and Icon components.

Categories
React Answers React Native

How to create a weather app with React Native?

(Source code is at https://github.com/jauyeunggithub/rook-hotel-answers/blob/master/q5.txt)

Sometimes, we want to create a weather app with React Native.

In this article, we’ll look at how to create a weather app with React Native.

How to create a weather app with React Native?

To create a weather app with React Native, we can make requests to a weather API to get weather data when someone enters a query in the search box.

For instance, we write:

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

// You can import from local files
import { useState, useEffect } from 'react';
import { Card } from 'react-native-paper';
import { TextInput, Button } from "react-native";


export default function App() {
  const [data, setData] = useState({});
  const [query, setQuery] = useState('');

  const getWeather = async () => {
    const res = await fetch(`https://www.metaweather.com/api/location/search/?query=${query}`);
    const [{woeid}] = await res.json();
    const resWeather = await fetch(`https://www.metaweather.com/api/location/${woeid}`);
    const d = await resWeather.json();
    setData(d);
  };

  return (
    <View style={styles.container}>
      <TextInput value={query} onChange={e => setQuery(e.target.value)} placeholder='Type Location to Search' />
      <Button title='Search' onPress={getWeather} />      
      <Card>
        {JSON.stringify(data)}
      </Card>
    </View>
  );
}

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

We define the data state to store the weather data.

And we have the query state to store the query input value.

Next, we define the getWeather function to make GET requests to the MetaWeather API with fetch.

And we call setData to set data to the result of the 2nd request.

Then we render a Virew with a TextInput to let users enter a query to search for weather data.

We have a Button which calls getWeather to make requests for the weather data according to the query value.

Then we display the retrieved data in a Card.

We add some styles to the View to center the content with justifyContent set to center and set a backgroundColor.

Conclusion

To create a weather app with React Native, we can make requests to a weather API to get weather data when someone enters a query in the search box.

Categories
React Native

React Native — JavaScript Environment, Network, and Security

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.

JavaScript Environment

React Native runs in an environment that lets us use modern JavaScript features.

In most cases, React Native lets us run with JavaScriptCore, which also powers Safari.

We can use most modern features like for-of, object spread, template literals, spread and rest, modules, async and await, and more.

Also, we can use popular methods like console.log , array methods, object methods, and more.

Timers and InteractionManager

We can use the InteractionManager object to run timers on a separate thread.

This is better than the alternative of using JavaScript timer functions like setTimeout and setInterval in our React Native code.

For example, we can write:

InteractionManager.runAfterInteractions(() => {
  // ...long-running synchronous task...
});

We run runAfterInteractions method with a callback and we can run any long-running synchronous code in the callback.

Networking

We can make HTTP requests with the Fetch API in our React Native app.

For example, we can write:

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

export default function App() {
  const [answer, setAnswer] = useState('');

  const fetchData = async () => {
    const res = await fetch('https://yesno.wtf/api');
    const { answer } = await res.json();
    setAnswer(answer);
  }

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

  return (
    <View style={styles.container}>
      <Text>{answer}</Text>
    </View >
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

to make an HTTP request to an API.

We make a request when we load the app with the useEffect callback and an empty array for the 2nd argument.

WebSocket Support

React Native has WebSocket support.

To connect to a socket and listen to the connection, we can write:

const ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  ws.send('something');
};

ws.onmessage = (e) => {
  console.log(e.data);
};

ws.onerror = (e) => {
  console.log(e.message);
};

ws.onclose = (e) => {
  console.log(e.code, e.reason);
};

The onopen method is run when we open the connection.

The onmessage method is run when a message is received.

onerror is run when an error occurred.

onclose method is run when the connection is closed.

Security

Like any other kind of apps, we’ve to think about security when we create our React Native app.

We should think about ways to store sensitive data.

To store environment variables, we can use the react-native-dotenv or react-native-config libraries.

We can use them to read things like API keys and other secrets from environment variables.

Secure Storage

To store data securely, we can use the Android Keystore to store items securely.

Also, we can use Encrypted Shared Preferences to store data.

Conclusion

We should think about security when we’re writing React Native apps.

Also, we can use the Fetch API to make HTTP requests from our React Native app.

Categories
React Native

React Native — Async Storage

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.

Async Storage

We can use the Async Storage library to store unencrypted data in our React Native app.

To install the library, we run:

yarn add @react-native-community/async-storage

Saving and Reading Data

Once we installed the library, we can import the library into our project and use it.

To do that, we write:

import React, { useState } from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

export default function App() {
  const [data, setData] = useState();

const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@storage_Key')
      if (value !== null) {
        setData(value)
      }
    } catch (e) {
      // error reading value
    }
  }

  const storeData = async (value) => {
    try {
      await AsyncStorage.setItem('@storage_Key', value)
    } catch (e) {
      // saving error
    }
  }

  return (
    <View style={styles.container}>
      <Button title='save data' onPress={() => storeData('foo')}></Button>
      <Button title='read data' onPress={getData}></Button>
      <Text>{data}</Text>
    </View >
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We import the AsyncStorage object.

And we use them in the getData function to get data and the storeData function to store the data.

The AsyncStorage.getItem method gets the data by its key.

And AsyncStorage.setItem takes the key and the value for the key and save the data into storage.

We can also write and read objects as value.

For example, we can write:

import React, { useState } from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

export default function App() {
  const [data, setData] = useState();

  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@storage_Key')
      if (value !== null) {
        setData(JSON.parse(value))
      }
    } catch (e) {
      // error reading value
    }
  }

  const storeData = async () => {
    try {
      await AsyncStorage.setItem('@storage_Key', JSON.stringify({ foo: 'bar' }))
    } catch (e) {
      // saving error
    }
  }

  return (
    <View style={styles.container}>
      <Button title='save data' onPress={storeData}></Button>
      <Button title='read data' onPress={getData}></Button>
      <Text>{data.foo}</Text>
    </View >
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We called JSON.stringify to convert the object into a JSON string in storeData .

The getData function parses the stringified object that’s read from getItem with JSON.parse .

Remove Data

There’s also the removeItem method to remove data to remove an item by the key.

For example, we can write:

import React, { useState } from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
export default function App() {
  const [data, setData] = useState();
  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@storage_Key')
      setData(value);
    } catch (e) {
      // error reading value
    }
  }
  const storeData = async (value) => {
    try {
      await AsyncStorage.setItem('@storage_Key', value)
    } catch (e) {
      // saving error
    }
  }

  const removeValue = async () => {
    try {
      await AsyncStorage.removeItem('@storage_Key')
    } catch (e) {
      // remove error
    }
  }

  return (
    <View style={styles.container}>
      <Button title='save data' onPress={() => storeData('foo')}></Button>
      <Button title='read data' onPress={getData}></Button>
      <Button title='remove data' onPress={removeValue}></Button>
      <Text>{data}</Text>
    </View >
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We call removeItem with the key in the removeValue function to remove an item with the given key.

Conclusion

The async storage library gives us an easy way to store data in an unencrypted manner with React Native.

Categories
React Native

React Native — Accessibility Props and Performance Issues

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.

accessibilityValue

We can add the accessibilityValue prop to describe the component’s state.

Its value is an object that can have some properties:

  • min — min value of a component’s range
  • max— max value of a component’s range
  • now — current value of a component’s range
  • text — text description of the component’s value

min , max , and now are integers and text is a string.

importantForAccessibility

The importantForAccessibility prop is only available to Android apps.

It controls whether a view fires accessibility events and if it’s reported to accessibility services.

For example, we can write:

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

export default function App() {
  return (
    <View accessible={true} importantForAccessibility="yes" style={styles.container}>
      <Text>
        hello world
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

onAccessibilityTap

onAccessibilityTap prop takes a function that’s called when someone activates an accessible element by double-tapping.

Accessibility Actions

We can add accessibility actions that let assistive technology programmatically invoke the actions of a component.

A component must define a list of actions it supports via the accessbilityActions property.

And it must implement the onAccessbilityAction function to handle action requests.

For example, we can write:

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

export default function App() {
  return (
    <View
      accessible={true}
      accessibilityActions={[
        { name: 'cut', label: 'cut' },
        { name: 'copy', label: 'copy' },
        { name: 'paste', label: 'paste' }
      ]}
      onAccessibilityAction={(event) => {
        switch (event.nativeEvent.actionName) {
          case 'cut':
            Alert.alert('Alert', 'cut action success');
            break;
          case 'copy':
            Alert.alert('Alert', 'copy action success');
            break;
          case 'paste':
            Alert.alert('Alert', 'paste action success');
            break;
        }
      }}
      style={styles.container}
    >
      <Text>
        hello world
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We add the props to our View so that we can show the alerts when those actions are executed.

Performance Problems

We should be careful when we’re creating our app.

One common source of slow performance is running our app in dev mode.

We should make sure we don’t do that with the production version.

Using console.log also slows down our app.

We should remove them as debugging.

When we want to use ListView s, we should replace them with FlatList or SectionList so that we get faster performance.

If we’re using ListView s, we should provide the rowHasChanged function checks whether the row has changed and needs to be re-rendered.

If we’re using touchable views, we won’t see any effect until the onPress function has returned.

If we set the state in the onPress function, then the touchable component may not look very responsive.

We can wrap our onPress actions in a requestAnimationFrame callback.

For example, we can write:

import React from 'react';
import { View, StyleSheet, TouchableNativeFeedback, Text } from 'react-native';
export default function App() {
  return (
    <View style={styles.container}>
      <TouchableNativeFeedback
        onPress={() => {
          requestAnimationFrame(() => {
            alert('You tapped the button!');
          });
        }}
      >
        <View style={styles.button}>
          <Text style={styles.buttonText}>TouchableNativeFeedback</Text>
        </View>
      </TouchableNativeFeedback>
    </View >
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

to callrequestAnimationFrame in our onPress callback.

Conclusion

We can add accessibility props and fix common performance problems easily with React Native.