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);