How To Develop NPM Packages Using TypeScript In React Native?

Previously I have given a demo on how to make a custom package in react native. In that, we learned how to create a package and how to manage it and then how to publish it to the npm registry. In that, we discussed and used the default example which is already available. So now in this blog, I’m going to explain to you how to create other custom components using typescript in react native

Here I will explain some basic details about Typescript but you can learn more about it by going to the given below links

Link1

Link2

What is TypeScript?

TypeScript is JavaScript for application-scale development.TypeScript is a strongly typed, object-oriented, compiled language.TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features.

Typescript improves your code and finds the mistakes in your code/editor.TypeScript checks a program for errors before execution and does so based on the kinds of values, it’s a static type checker. TypeScript is JavaScript’s runtime with a compile-time type checker.

With Typescript :

type Result = “pass” | “fail” function verify(result: Result) { if (result === “pass”) {

   console.log(“Passed”)

 } else {

   console.log(“Failed”)

 }

}

Normal JS:

function verify(result) { if (result === “pass”) {   console.log(“Passed”) } else {

   console.log(“Failed”)

 }

}

How to declare the shape of an Object?

There are two main ways to declare the shape of an object in Typescript: interfaces and type aliases. Both are very similar and perform the same kind of operation in most cases. Almost all features of an interface are available in type, the key distinction is that a type cannot be reopened to add new properties vs an interface that is always extendable. You can check more in :

  1. Stackoverflow
  2. Typescriptlang

Syntax can be follow like given below :

type BirdType = {

 wings: 2;

};

interface BirdInterface {

 wings: 2;

}

And you can use them as given below :

const bird1: BirdType = { wings: 2 };

const bird2: BirdInterface = { wings: 2 };

TypeScript supports an extension of the JavaScript language, which offers places for you to tell TypeScript what the types should be. For example, to create an object with an inferred type that includes name: string and id: number, you can write:

const user = {

 name: "Hayes",  id: 0,

};

You can explicitly describe this object’s shape using an interface declaration:

interface User {

 name: string;

 id: number;

}

You can then declare that a JavaScript object conforms to the shape of your new interface by using syntax like TypeName after a variable declaration:

const user: User = {

name: "Hayes",

id: 0,

};

You can learn more about typescripts from the given links. So now we are moving to implement modules and files for making custom packages.

Implementation

In the src or source folder create one new file named CustomLoader.tsx now that we write for our components.

1. Import libraries:

2. Now you can define Props using type keyword OR interface. Currently, I define props on a prior basis but you can add more props based on component requirements. This means if we need more props like value,onChange, getvalue, etc.. you can add new props with the required type anytime.

Using type keyword

OR 

Using interface keyword

Here you can see I have taken props and their types based on requirements for loading I take boolean type, for color, I take string type.

If we need any props from react-native built-in APIs like View’s style then we need to write like StyleProp<ViewStyle>. So basically it says that we need Style Prop of View API’s style. So when we use this containerStyle prop we need to pass the required style of react-native View.

If we want to create props that value needs to be selected from the given selected list so we can create props like this “small” | “large” |number, so we need to select values from these two. If we pass another value for that prop it will give an error.

 

Now we are going to the main design and logic part where our module will be written. We will use the function component for creating the custom activity indicator module. So we will use React.FC means React’s function component. It provides type checking and autocompletes for static properties like displayName, propTypes, and defaultProps.

We need to implement the design part same we are implementing it in Javascript/React-Native. Our basic syntax will look like this

const CustomLoader: React.FC<TypeProps> = ({

    loading,

    color,

    size,

    containerStyle,

    activityIndicatorProps,

}) => {

    return (

        <React.Fragment>

            

        </React.Fragment>

    )

}

Here CustomLoader is our component name/modulename. React.FC will take TypeProps as inherited props for TypeChecking and then we need to do design normally as we are doing in react-native javascript. So Here loading prop requires the boolean value from where our component will be imported. Because we declared type boolean for that loading prop. So based on that other props need their defined value like string, style, function, etc.

So here in the screenshot below I have written the full component. You can check it.

We also need to define the type of params when we are implementing the regular function like only for operation/action purposes.

/**

 * 

 * @param appName for Display App Name

 * @param message for Display message 

 * Show simple alert

 */

export function showSimpleAlert(appName: string, message: string) {

   Alert.alert(

      appName,

      message,

      [

         { text: "OK", onPress: () => { } }

      ],

      { cancelable: false }

   );

}

So here we need the appName and message in string format as params while we are calling the showSimpleAlert method. 

We can also define what kind of data will return after calling any function or method like we will get a boolean value or any response or number value, etc. We can provide the resulting value using Promise and return value you can set Promise<type> like given below.

Now we have to import and export all modules from the index.tsx file, so we can use it in other projects.

Now you can add examples in the README.md file and also in the example folder’s App.tsx file as per your requirement.

Then you can update your package version every time when you need to publish and update a package in the npm registry. You can also add keywords based on your features.

Now you can upload and push your code to the git repository. You can refer to the commands below.

  • git status
  • git add -a
  • git commit -m “your message”
  • git push origin/git push –set-upstream origin master.

You can upload your package to the npm registry using the below command.

npm publish
coma

Conclusion

This article is helpful to the developers who want to make their own custom packages using typescript in react native and want to use them in their private packages. In this, I also gave some understanding of TypeScript. Typescript is a very useful language for type checking and also useful for deciding coding standards.TypeScript can catch bugs when we make mistakes in our code. Using Typescript with a custom module we can provide a better way to use the module for understanding modules and which props and data are required to implement. The reader should now be equipped with the tools and workflow to develop their own packages with TypeScript in React Native.

Developers can follow the GitHub link to check the custom package:: here

!! Enjoy, Keep and Do Delicious Coding !! 🙂🙂

Ronak K

React-Native Developer

Ronak is a React-Native developer with more than 4 years of experience in developing mobile applications for Android and iOS. He is dedicated to his work and passion. He worked in different kinds of application industries that have responsive designs. He also has knowledge of how to make an app with expo cli and react-native web and some basic understanding of react.js.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!