Day 5: Handling Text Input
Recap:
Today being day 5 of my #ReactNativeIn30days series, I will like to go over what I have covered in the past 4 days. So far, I have touched on topics such as why the need to use React Native(why, what, who, etc…), setting up a development environment using expo, the building block of React Native which are components (e.g. View, Text, etc.), and finally state and props.
With what I’ve covered so far, I was able to run a basic React Native application that prints out text to the browser. Also, I added some state to the application and experimented with how state and props work together.
What we’ll be looking at:
Today, I will cover how to handle user input through a text input field. I will build a simple login form to show how the state of the application is changed in real-time.
Besides most of the applications we use on a daily basis, be it twitter, what’s app, or Instagram has some form of interactivity where user inputs are taken. For example, when you open most applications for the first time, you are asked to either login or sign up and this is one way of accepting user input.
The code
Below are screenshots of my source code with detailed explanations under each.
Line 1 — Line 2: At line 1 we import React and useState from the react library. useState allows us to define state within our functional component (App).
At line 2, we import some important widgets such as View (acts as div in the web), Text (allows us to output text), TextInput (create text input) and StyleSheet( to add styling to our app).
Line 4: At line 4, we define our stateless functional component called App and export it on line 55.
Line 3 — Line 4: Here we set the state of the app by initializing name and age with some default values
Line 8 and Line 12: I defined two methods, handleNameChange and handleAgeChange. What these two methods basically do is that they set the state whenever an onChangeText event is triggered.
Line 16: In the return body, at lines 18 and 19, we grab the initial value of our state which are name and age.
Line 22 and 28: We create our text input fields which change the initial value of our state when an onChangeText event is triggered, hence updating the state of our application.
Final Result:
Github Repo :https://github.com/victorbruce/react-native30