JustDucky
JustDucky

Reputation: 132

TypeError: undefined is not an object in React-Native

I'm really new to Javascript and ReactJS, and am baffled by the error TypeError: undefined is not an object (evaluating '_this.state = { destination: '' }')

Here is my code:

import React, {Component} from 'react';
import { StyleSheet, View, TextInput } from 'react-native';

export default class SearchBar extends Component {
    constructor() {
        /*
        this.state = {
            destination: ''
        };
        */
        super();
    }
    render() {
        return (
            <View style={styles.inputContainer}>
                <TextInput
                    style={styles.input}
                />
            </View>
        );
    }
}

This code works fine. But as soon as I uncomment

this.state = {
            destination: ''
        };

I get the error. Why is it bugging me about it being undefined? I'm not accessing it anywhere.

This might look like a duplicate of the question here but the difference is that in that question, the solution involves using .bind(this) on a function the asker defined. I have no such function I can call this on.

Any help would be greatly appreciated.

Upvotes: 0

Views: 1264

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76508

this is configured by super. Before super is executed, this is not configured yet. This is the reason of the problem you have experienced. Fix:

constructor(props) {
    super(props);
    this.state = {
        destination: ''
    };
}

Upvotes: 1

Related Questions