How to create a reusable input component with custom mask in react native

Vinicius Petrachin
3 min readFeb 19, 2022

--

Application Home Screen

Hello everyone, in this tutorial I’m going to show you how you can create a reusable input component with parameters for you to parameterize, that way you can dynamically generate it according to the desired mask.

example

We will create a masks.ts file for you to store the functions that applied the desired mask. We will work with regular expressions (REGEX) and the javascript replace function.

In this tutorial I will be using typescript, because it is widely used and it was also more than clear that it is here to stay. But for beginners or non-adepts I’ll be leaving the code in javascript as well.

Technologies that will be used

Typescript / Javascript
RegEx
React Native

Let’s get started

I already created a basic structure in my project, just for displaying the inputs, and also a simple layout for the inputs. That’s because the tutorial consists of teaching how to put on the mask and not the stylization, which could be done in future tutorials :)

  1. App.tsx

2. Create a file called masks.ts inside the utils folder. So it will be easy to always use this file, maintain it and also add new masks in the future.

3. Create an index.tsx file inside the components/input folder, thus making it components/input/index.tsx. With this organization it will be easier to reuse your components and it will be following a widely used pattern.

For those who want the application code in javascript only, I left it in this github directory.

https://github.com/viniciuspetrachin/component-input-text-with-mask-react-native

Well now it’s time for you to have an application with the desired effect. In the tutorial I used the Brazilian format for telephone and the currency mask in the American standard. You can find other regex to apply in the app now.

Final result

Always update this mask file, creating new masks whenever you need it and also create it outside your application so that you can use it in other projects.

You can be sure that this is of great help, many projects need it and if you follow this tip you will greatly optimize your development time.

Thanks to everyone who read this far. I ask you to leave a feedback, tip, or suggestion below to encourage me to improve and bring you better tutorials.

See you later!

--

--

Vinicius Petrachin
Vinicius Petrachin

Written by Vinicius Petrachin

Experienced React Native developer with a passion for mobile app development. Focusing on reaching seniority in React Native!

No responses yet