1. 6
    Accept User Input with React Native TextInput
    2m 35s

Accept User Input with React Native TextInput

Chris Achard
InstructorChris Achard

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

In this lesson, we’ll accept user input for the first time with a text box. We’ll operate the text input as a controlled component, and store the text value in our component state. We’ll use that text input to perform a live search on the elements in the list.

Instructor: [00:00] Import TextInput from React native. which is a text box that we can use to accept the user search query. Just below the header and above the list, put in a TextInput tag.

[00:12] When we reload, we can see a bit of extra space there, but we can't actually see the input box. If you select just the right location, you can see a cursor blink, which shows that the TextInput box is actually there.

[00:26] Let's add some styles to it to make it much more clear. We can call the styles input and put them in the app's style sheet. We'll add some separation with the bottom margin, create some padding, and put some larger text padding on the left and right side with padding horizontal.

[00:46] The text inside a TextInput component can also be styled like a normal text component. We can set the font size and the color of the text on the TextInput directly. Then we can add a border and background like any other React native view.

[01:02] Note that styling borders in React native is a bit different than on the web. We have to specify a border width and a border color separately. Now if we reload that, it looks quite a bit better, though it's a still bit unclear that it's a search box.

[01:18] We can add some placeholder text with a prop called placeholder, which makes it more clear that it's a search box. Now that we have a TextInput styled, let's do some live filtering as the user types into the TextInput.

[01:35] TextInput components accept a prop called onChangeText. Let's set that. This is different than on the web where inputs accept an onChange prop. The nice thing about onChangeText is that it passes the current text directly instead of as an event.

[01:52] We'll use the return text to set a bit of state called search. We should make sure search exists when the component loads. Also, we'll make the TextInput a controlled component by setting the value to the current value of search.

[02:08] Now we can use that search to actually filter the restaurants in the web view by adding a filter statement to the map, which will only show restaurants if the search is blank, or if the lowercase of the restaurant contain the lowercase of the search query.

[02:25] When we reload, we can add type into the search box and properly filter the list in real time.