Reputation: 145
I have written a react component with a constructor, methods, and render. When I comment out the methods and have only the render and constructor everything is fine, but when I add the methods the first always comes up as undefined unless I close off the whole class after the constructor.
Here is my class (since it doesn't matter what is in the methods I just put the declarations for brevity):
export default class App extends Component {
constructor(props) {
super(props);
const allWords = ["word", "pipe", "dear", "deer", "fish", "coat"];
const word= allWords[Math.floor(Math.random()*allWords.length)];
var lettersFound = [];
for (var i=0; i<word.length;i++) {
lettersFound = [...lettersFound, [i, "_"]];
}
this.fillWord = this.fillWord.bind(this);
this.state = {
word: word,
numWrongGuesses: 0,
lettersGuessed: [],
lettersFound: lettersFound,
error: ""
}
}
isLetterInWord = (letter) => {
}
fillWord = () => {
}
handleGuess = (letter) => {
}
render () {
return (
<div className="App">
</div>
);
}
}
This doesn't compile, giving the error "'isLetterInWord' is not defined". If I remove this function, the error is thrown on fillWord instead. If I add a "}" after the constructor the methods are all defined but render throws an unexpected token error on the return line. I do not understand why I would want to close off the class after the constructor, or why it isn't compiling as is.
Upvotes: 3
Views: 6882
Reputation: 545
Try to bind the function inside the constructor like this:
this.isLetterInWord = this.isLetterInWord.bind(this);
this.fillWord = this.fillWord.bind(this)
this.handleGuess = this.handleGuess.bind(this);
Upvotes: 5
Reputation: 107
Here you are defining class properties, which is currently (I think) is stage-3 proposal. In other words it is not supported by default. May be because of this you are getting errors. You can use class-properties-transform plugin for Babel to add support of this syntax though if you want to .
isLetterInWord = (letter) => {
}
fillWord = () => {
}
Try defining methods as and see if it works
isLetterInWord(letter) {
}
Upvotes: 2