We are going to make a TextInput component which will be custom and can be used and styled anytime in the app wherever needed.
Why to make custom component?
Sometimes or in most of the cases we need to use same type of component in our app multiple times in multiple screens such as Button, TextInput etc., so better we make a custom component of it. Stylings and values of it will be dynamic as per we pass while calling it. So we just need to save it in the separate folder to use and style it as per required.
Let’s start making our custom Text Input component.
1. Let’s first Install required packages/modules in your React Native project
We just need to install 2 packages:
Run following command in Terminal of your React Native project directory
npm i styled-components
React Native Vector Icons is a well-known library that has more than 3000 icons that are completely free to be utilized. React native vector icon libraries include icons like navigation buttons, bars, logos, tab bars, and more. All the icons for this library are highly interactive that can make your React Native project more interesting. Know more about it here.
npm i react-native-vector-icons
CustomInputField.jsfile in your project
I have created the file in
src > components > CustomInputField.js
You can create this file directly in your project but it’s good to arrange your projects files/folders in the better way to solve the problem of mix-matching the files, as it will help you in future to find specific file even if the number of files/folders increases in your project.
3. Import required packages
CustomInputField.js and import required packages like below
4. Make a component class CustomInputField
after making a class we need to structure prop values inside
render() function as below, in order to directly use prop values without using
Now, we need to design our CustomInputField class component. Inside the
return() function we need to design our component like below
In the above code where we used
prefixIcon && this is just a condition which means if the value of
prefixIcon is not
0 then return the component which is initialized on right side of
So, from this condition if there is value passed in the prefixIcon then it will be rendered otherwise not.
Now, we need to style our components outside the
CustomInputField class as below
Now, we are all set and have made our custom component successfully
CustomInputField class component and call it. Pass props as per your requirement for example, if you need to show prefixIcon in the TextField just pass the name of the Icon (You can browse Material Icons and their names here MaterialIcon)
🎉 Hurray! you made your custom component. Hope you understood how we made it. If you’re still facing any problem making it or have doubts or anything else please leave a comment i’ll definitely look up to it.
Thank you 🙏