I am trying to build a word dictionary that translates English words to German words by following this tutorial. It utilize a json file which, I believe, contain keys with English words and its corresponding German words as values.
The tutorial do that by using the require statement
var english_german = require('./english_german.json');
but I would like to know if there is an alternative by using the import statement instead.The main problem I am facing, though, is that I am getting a "Undefined is not an Object (evaluating 'this.state.input')" error when I type in a word in the TextInput and hitting enter.
My source code is as follows:
import React, { Component } from 'react';
import {
AppRegistry,
Image,
StyleSheet,
Text,
TextInput,
View
} from 'react-native';
var english_german = require('./english_german.json');
class Dictionary extends Component {
constructor(props) {
super(props);
this.state = {
input: '',
output: ''
}
}
showMeaning() {
// Use the ternary operator to check if the word
// exists in the dictionary.
var meaning = this.state.input in english_german ?
english_german[this.state.input] :
"Not Found";
// Update the state
this.setState({output: meaning});
}
render() {
var layout =
<View style = { styles.parent }>
<Text>
Type something in English:
</Text>
<TextInput
onChangeText={(e) => this.setState({input: e})}
text = { this.state.input }
onSubmitEditing = { this.showMeaning }
/>
<Text style = { styles.germanLabel }>
It's German equivalent is:
</Text>
<Text style = { styles.germanWord }>
{ this.state.output }
</Text>
</View>
;
return layout;
}
}
const styles = StyleSheet.create({
// For the container View
parent: {
padding: 16
},
// For the Text Label
germanLabel: {
marginTop: 20,
fontWeight: 'bold'
},
// For the Text meaning
germanWord: {
marginTop: 15,
fontSize: 30,
fontStyle: 'italic'
}
});
AppRegistry.registerComponent('Dictionary', () => Dictionary);
This is because you are referring to
this
inside ofshowMeaning
. Bind that function to rightthis
insideconstructor
like thisthis.showMeaning = this.showMeaning.bind(this)
.I highly recommend you to read basics of React. For example here is documentation for your problem: https://facebook.github.io/react/docs/handling-events.html
This is a binding problem, add this in your constructor:
This will ensure that
this
object in yourshowMeaning
method refers to yourDictionary
component. Alternatively, you could use arrow function in yourshowMeaning
method like so:The arrow function preserves the context of
this
. So the use ofbind
isn't required.