React native typescript: Why and how to use it to build an application

Are you a web/app developer? So you must know TypeScript. Because with over 19 million weekly downloads on npm, TypeScript is becoming the favorite pick of developers. Furthermore, TypeScript is likely to appear in two of every three JavaScript-related job descriptions. That is the reason why in this blog, ArrowHiTech will mention React native typescript: Why and how to use it to build an application. Therefore, don’t miss any information in this article. 

What is typescript?

React native typescript

TypeScript is known as an open-source language that was built based on JavaScript by Microsoft. TypeScript is similar to JavaScript, but with static type definitions. Furthermore, there are two parts in TypeScript:

  • Syntax: let x: string = ‘y’
  • A transpiler: takes TypeScript and translates it to JavaScript.

Also read: React native web view: The comprehensive guide you need to know

Should you use React native typescript?

Pros of React native typescript

  • Firstly, Self documenting: You document the values you want from a function or component by specifying types.
  • Secondly, Debugging is simpler: When you expect a boolean, you pass a string of true. TypeScript will inform you of your errors.
  • Thirdly, Refactoring that is less complicated: Have you forgotten to rename a function or change an argument’s value? TypeScript will inform you of this.
  • Fourthly, Allow your text editor/IDE to assist you more: TypeScript is compatible with almost all editors. This allows your editor to complete automatically. Moreover, it also inform you what to supply to a function/component using TypeScript
  • Insert structure to larger apps: By identifying how your app operates, you’ll be obliged to consider it in relation to the rest of the app. You can also avoid the “traps” that JavaScript can lead to 
  • Validity JS is guaranteed: In case you use valid TypeScript. So you may be confident that you’ll get correct JavaScript output. Because it runs at the target level you define. However, you will not get that guarantee if you write straight JavaScript (that isn’t transpiled).
  • Finally, Can be implemented gradually: You don’t have to use TypeScript completely. Valid JavaScript is still valid TypeScript. So you don’t have to dive right in at the start. Therefore, you have the option to test the waters.

Cons of React native typescript

  • Firstly, Another dependency to keep track: You must manage a dependence, understand its settings, and maintain it up to date if you add one. Because nothing comes for free.
  • Secondly, New/different syntax: It’s almost like learning a new language. In case you’re used to writing JavaScript. So you have to wait a little bit to become used to the new syntax.
  • Thirdly, Different/additional tooling: The TypeScript transpiler has been added to your workflow. Therefore, it’s just one more thing to deal with.
  • Fourthly, Slow down: Typing your code has a lot of advantages. However, you still have to write those kinds. This will first slow you down. But it has significant advantages (see above pros)
  • Fifthly, Types of third-party packages: Some packages provide third-party package types (such as React Navigation). Whereas others require you to add another requirement. Others simply lack them. However TypeScript can infer things automatically).
  • Finally, Talent pool: JavaScript is more popular than TypeScript. However, anyone who knows JavaScript can learn TypeScript. Because now it has a rapidly increasing user base.

How to use React native typescript to build an application?

Requirements

  • Firstly, knowledge of how to run CLI commands is required.
  • Secondly, on your device, you should have Node.js and npm installed.
  • Thirdly, you must have XCode or Android Studio installed on your device.
  • Fourthly, JavaScript knowledge is required.
  • Fifthly, React knowledge is required.
  • Finally, some knowledge of React Native (suggested, not required)

Get started 

In your terminal, type the following command:

React native typescript

Firstly, the command above will create a new React Native project with the appropriate dependencies and configurations in a folder called ShoppingList, using a TypeScript template.

Therefore, take a look at the documentation to see how TypeScript can be used in an existing application

Creating the base user interface

To begin the project, open the folder in your code editor and enter the commands following (based on your device):

# MacOS

npm run ios

# Windows/Linux

npm run android

Firstly, the base component in the app is the App.tsx component. Secondly, you should construct a folder structure in the root folder, such as src/components, and a Header.tsx component in the components folder.

In this case, we’re now using TypeScript. Besides that, we need to utilize the correct file extensions; otherwise, the regular.js files would cause errors. Therefore,  the files have a .tsx extension.

Therefore, Copy and paste the following code into the file:

import React from ‘react’;

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

interface Props {

  title: string;

}

const Header: React.FC<Props> = ({title}) => {

  return (

    <View style={styles.header}>

      <Text style={styles.headerText}>{title}</Text>

    </View>

  );

};

const styles = StyleSheet.create({

  header: {

    paddingVertical: 20,

    borderBottomWidth: 1,

    borderBottomColor: ‘#cfcfcf’,

    alignItems: ‘center’,

  },

  headerText: {

    fontSize: 20,

    fontWeight: ‘600’,

  },

});

export default Header;

In case you’re experienced with React Native. Therefore, you can skip most of the code above;  However, I’d like to highlight lines 3-6:

React native typescript

We defined an interface in the first three lines, which acts as the basis for the props object we’d ordinarily access in our component. However, in here we’re using TypeScript to provide the props and their types.

The advantage of implementing it this way is that we get improved IntelliSense and some validation since we use the component. For example, there will be an instant error if the title is not supplied to the component. 

Change the content in the App.tsx component with the following code:

import React from ‘react’;

import {SafeAreaView, StyleSheet, Text, View} from ‘react-native’;

import Header from ‘./src/components/Header’;

const App = () => {

  return (

    <SafeAreaView style={styles.container}>

      <Header />

    </SafeAreaView>

  );

};

const styles = StyleSheet.create({

  container: {

    flex: 1,

    backgroundColor: ‘#e8e7e3’,

  },

});

export default App;

In this case, a red line should appear below the Header/> component. when you hover your mouse over it. Thus, you should receive a warning indicating that the component is missing a title prop. So let’s get started right now. Therefore, change that lines with the code snippet following, and the error should be disappeared:

<Header title=”Shopping List” />

You’ll get a different error in case you try to assign a number (or other data type which is not a string). TypeScript is attempting to assist you in detecting issues before they occur.

Insert items to the list

Add the following code to a new component called AddItem.tsx in your /src/components folder:

import React, {useState} from ‘react’;

import {

  View,

  Text,

  TextInput,

  TouchableOpacity,

  StyleSheet,

} from ‘react-native’;

export interface IItem {

  item: string;

  quantity: string;

}

const AddItem = () => {

  const [item, setItem] = useState(”);

  const [quantity, setQuantity] = useState(”);

  return (

    <View>

      <Text style={styles.heading}>Add Shopping Item</Text>

      <View style={styles.form}>

        <TextInput

          style={styles.input}

          placeholder=”Enter item”

          value={item}

          onChangeText={text => setItem(text)}

        />

        <TextInput

          style={styles.input}

          placeholder=”Enter quantity”

          keyboardType=”numeric”

          value={quantity}

          onChangeText={q => {

            setQuantity(q);

          }}

        />

        <TouchableOpacity style={styles.addItemButton} onPress={() => {}}>

          <Text style={styles.buttonText}>Add Item</Text>

        </TouchableOpacity>

      </View>

    </View>

  );

};

const styles = StyleSheet.create({

  heading: {

    fontSize: 20,

    fontWeight: ‘700’,

  },

  form: {

    marginTop: 30,

  },

  input: {

    padding: 15,

    borderColor: ‘rgba(0, 0, 0, 0.2)’,

    borderWidth: 1,

    borderRadius: 5,

    marginBottom: 20,

  },

  addItemButton: {

    backgroundColor: ‘#eb8634’,

    paddingVertical: 20,

    borderRadius: 5,

    alignItems: ‘center’,

  },

  buttonText: {color: ‘#fff’, fontWeight: ‘500’},

});

export default AddItem;

Return to App.tsx and update the component with the following code:

import React, {useState} from ‘react’;

import {SafeAreaView, StyleSheet, Text, View} from ‘react-native’;

import Header from ‘./src/components/Header’;

import AddItem, {IItem} from ‘./src/components/AddItem’; /* import AddItem and interface*/

const App = () => {

  const [shoppingList, setShoppingList] = useState<IItem[]>([]); // set the type of what the hook expects to be an array of IItems.

  return (

    <SafeAreaView style={styles.container}>

      <Header title=”Shopping List” />

      <View style={styles.contentWrapper}>

        <AddItem

          setShoppingList={setShoppingList}

          shoppingList={shoppingList}

        />

      </View>

    </SafeAreaView>

  );

};

const styles = StyleSheet.create({

  container: {

    flex: 1,

    backgroundColor: ‘#e8e7e3’,

  },

  contentWrapper: {

    padding: 20,

  },

});

export default App;

Now that the new AddItem component and the IItem interface have been imported into App.tsx. As a result, we can use the useState hook to build the shoppingList state (on line 6).

When using the setShoppingList function, the hook must accept an array of IItem. In case you mouse over the setShoppingList. So The type is visible

Return to the AddItem.tsx component and make the following changes:

import React, {useState} from ‘react’;

import {

  View,

  Text,

  TextInput,

  TouchableOpacity,

  StyleSheet,

  Alert,

} from ‘react-native’;

export interface IItem {

  item: string;

  quantity: string;

}

interface Props {

  setShoppingList: React.Dispatch<React.SetStateAction<IItem[]>>;

  shoppingList: IItem[];

}

const AddItem: React.FC<Props> = ({shoppingList, setShoppingList}) => {

  const [item, setItem] = useState(”);

  const [quantity, setQuantity] = useState(”);

  const addItem = () => {

    if (!item) {

      Alert.alert(‘No Item!’, ‘You need to enter an item’);

    } else {

      setShoppingList([

        …shoppingList,

        {

          item,

          quantity: quantity || ‘1’,

        },

      ]);

      setItem(”);

      setQuantity(”);

    }

  };

  return (

    <View>

      <Text style={styles.heading}>Add Shopping Item</Text>

      <View style={styles.form}>

        <TextInput

          style={styles.input}

          placeholder=”Enter item”

          value={item}

          onChangeText={text => setItem(text)}

        />

        <TextInput

          style={styles.input}

          placeholder=”Enter quantity”

          keyboardType=”numeric”

          value={quantity}

          onChangeText={q => {

            setQuantity(q);

          }}

        />

        <TouchableOpacity style={styles.addItemButton} onPress={addItem}>

          <Text style={styles.buttonText}>Add Item</Text>

        </TouchableOpacity>

      </View>

    </View>

  );

};

const styles = StyleSheet.create({

  heading: {

    fontSize: 20,

    fontWeight: ‘700’,

  },

  form: {

    marginTop: 30,

  },

  input: {

    padding: 15,

    borderColor: ‘rgba(0, 0, 0, 0.2)’,

    borderWidth: 1,

    borderRadius: 5,

    marginBottom: 20,

  },

  addItemButton: {

    backgroundColor: ‘#eb8634’,

    paddingVertical: 20,

    borderRadius: 5,

    alignItems: ‘center’,

  },

  buttonText: {color: ‘#fff’, fontWeight: ‘500’},

});

export default AddItem;

We have already created the Props interface on line 14. And then we also specified the type of each property. After that, on line 18 we have to define it as the props type in our functional component.

On line 21, we also added a handler code. Therefore, it will check if an item has been put in the field. After that, it will use the setShoppingList() function to insert a new item to the list when the “Add Item” button is pressed.

Creating a list of items

Create a new file called Item.tsx in /src/components and add the following code inside:

import React from ‘react’;

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

import {IItem} from ‘./AddItem’;

const Item: React.FC<IItem> = ({item, quantity}) => {

  return (

    <View style={styles.item}>

      <Text style={styles.itemName}>{item}</Text>

      <Text style={styles.quantity}>x{quantity}</Text>

    </View>

  );

};

const styles = StyleSheet.create({

  item: {

    padding: 20,

    flexDirection: ‘row’,

    justifyContent: ‘space-between’,

    alignItems: ‘center’,

    borderBottomWidth: 1,

    borderBottomColor: ‘rgba(0, 0, 0, 0.2)’,

  },

  itemName: {

    fontWeight: ‘500’,

  },

  quantity: {

    padding: 6,

    borderWidth: 1,

    borderColor: ‘rgba(0, 0, 0, 0.2)’,

    borderRadius: 10,

    overflow: ‘hidden’,

    backgroundColor: ‘rgba(0, 0, 0, 0.05)’,

  },

});

export default Item;

We’ll now finish by importing the component into App.tsx and using the built-in [FlatList] component to display the items.

Replace the contents of App.tsx with the following code:

import React, {useState} from ‘react’;

import {SafeAreaView, StyleSheet, View, FlatList} from ‘react-native’;

import Header from ‘./src/components/Header’;

import AddItem, {IItem} from ‘./src/components/AddItem’;

import Item from ‘./src/components/Item’;

const App = () => {

  const [shoppingList, setShoppingList] = useState<IItem[]>([]);

  return (

    <SafeAreaView style={styles.container}>

      <Header title=”Shopping List” />

      <View style={styles.contentWrapper}>

        <AddItem

          setShoppingList={setShoppingList}

          shoppingList={shoppingList}

        />

        <FlatList

          data={shoppingList}

          keyExtractor={(item, index) => `${item.item}-${index}`}

          renderItem={({item}) => (

            <Item item={item.item} quantity={item.quantity} />

          )}

        />

      </View>

    </SafeAreaView>

  );

};

const styles = StyleSheet.create({

  container: {

    flex: 1,

    backgroundColor: ‘#e8e7e3’,

  },

  contentWrapper: {

    padding: 20,

  },

});

export default App;

So the process is now finished. On line 16, we use the FlatList component to show items from the list

Conclusion

Above is all information about React native typescript. Are you all clear? In case you are still confused with any step in this article. So please let ArrowHiTech know. ArrowHiTech has an expert team of react native developers. We are so proud of being the primary choice of customers in a short span of time.

Tags

Share