Hello,
I have been building the JavaScript calculator app in React for a couple of days. I’ve almost passed all the tests, but I can’t seem to figure out this error that stops test #14 from succeeding (14. Pressing an operator immediately following “=” should start a new calculation that operates on the result of the previous evaluation).
When I press a number or operator button after performing a single calculation (any number/operator combination followed by the “=” equals button) I get the error:
Uncaught TypeError: _this.state.input.indexOf is not a function
Here’s the code in question:
constructor(props) {
super(props);
this.state = {
input: "0"
};
}
addToInput = value => {
if (this.state.input.indexOf("0") === 0) {
this.setState({
input: "" + value
});
} else if (
this.state.input.lastIndexOf(".") === this.state.input.length - 1 &&
value === "."
) {
return;
} else if (
this.state.input.lastIndexOf(".") === this.state.input.length - 2 &&
this.state.input.length >= 2 &&
value === "."
) {
return;
} else {
this.setState({
input: this.state.input + value
});
}
};
handleEquals = () => {
this.setState({ input: eval(this.state.input) });
};
(below is example code for one of my buttons)
<Buttons id="seven" handleClick={this.addToInput}>
7
</Buttons>
(this is from the Buttons component)
<div
id={props.id}
onClick={() => props.handleClick(props.children)}
>
{props.children}
</div>
I have tried binding my functions to ‘this’ in the constructor, as well as using arrow functions in my render. I believe that I’m losing ‘this’ in the addToInput function after executing the handleEquals function once. I just don’t know how to fix it.