0

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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
JustDucky
  • 132
  • 1
  • 10
  • 4
    It could be a very misleading error caused by the fact that you try to define `this.state` before calling `super()`. `this` is not available in the constructor before `super()` has been called. You should also take the `props` argument in the constructor and pass it on to `super`, i.e. `constructor(props) { super(props); ...` – Lennholm Jun 28 '20 at 22:32

1 Answers1

1

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: ''
    };
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175