Sergei Mikhailovskii
Sergei Mikhailovskii

Reputation: 2465

undefined is not an object while getting text from TextInput in Expo project

I'm a newbie in RN development and faced with the following problem: when I created RN project with Expo I deleted everything from screen and added necessary components. So, I have a TextInput, which should add data to variable. So, that's why I created property in state: this.state = {text: ''};, which will keep this data. But when I run project I have this error: undefined is not an object. Here's the code of my screen:

export default function HomeScreen() {

    this.state = {text: ''};

    return (

        <View style={styles.container}>
            <ScrollView
                style={styles.scrollViewContainer}
                contentContainerStyle={styles.contentContainer}>
                <View style={styles.searchContainer}>

                    <TextInput
                        placeHolder="Type something!"
                        onChangeText={(text) => this.setState({text})}
                        value={this.state.text}
                    />

                </View>

                <View>

                    <Button
                        onPress={Alert.alert("Button pressed!")}
                        title="Search"
                    />

                </View>

                <View style={styles.listContainer}>

                    <Text>{this.state.text}</Text>

                </View>

            </ScrollView>


        </View>
    )
        ;
}

So, maybe this question is stupid, but please, explain what the matter and how can I solve this problem. And maybe there are some other moments in code, which should be changed?

Upvotes: 0

Views: 87

Answers (3)

gonpeche
gonpeche

Reputation: 99

The onPress should call a function. Try this way:

<Button
  onPress={() => Alert.alert("Button pressed!")}
  title="Search"
/>

This same example is explained in the Handling Touches docs:

Hope it helps,

Upvotes: 2

Ilphrin
Ilphrin

Reputation: 42

If you use a functional component, you should definitely use Hooks instead of a state object, but as you are using Expo I guess the version of React and React Native used is too old to have Hooks enabled

Change your component to a Class Component, so in the constructor you can have a state object, and use it in your render method

Upvotes: 0

Kaushik Radadiya
Kaushik Radadiya

Reputation: 383

Instead of this.state = {} use only state= {text: ''}

More info: https://www.robinwieruch.de/react-state-without-constructor/

Upvotes: 2

Related Questions