I am trying to build the calculator from Freecodecamp's front end projects. And I am using the eval() function with pressing the equals button.
Here is the child component
class Equals extends React.Component {
constructor(props) {
super(props);
this.handleEquals = this.handleEquals.bind(this)
}
handleEquals = () => {
this.props.handleClick(eval(this.props.exp))
}
render() {
return (
<button id='equals' onClick={this.handleEquals}>=</button>
)
}
}
And here is the parent component
class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
numPad: numPad,
operations: operations,
prevVal: [],
currVal: '',
display: '',
expression: []
}
this.handleDisplay = this.handleDisplay.bind(this);
this.clearDisplay = this.clearDisplay.bind(this);
}
handleDisplay = input => {
this.setState({
currVal: input,
prevVal: this.state.prevVal.concat(this.state.currVal),
display: this.state.prevVal.concat(this.state.currVal).concat(input),
expression: this.state.prevVal.concat(this.state.currVal).concat(input)
})
}
handleEvaluate = input => {
this.setState({
display: input
})
}
clearDisplay() {
this.setState({
prevVal: '',
currVal: '',
display: '0'
})
}
render() {
return (
<div>
<div id='display'>{this.state.display}</div>
<Equals exp = {this.state.expression} handleClick = {this.handleEvaluate}/>
{this.state.numPad.map(num =>
<NumPad dig={num.dig} wrd={num.wrd} handleClick={this.handleDisplay}/>)}
{this.state.operations.map(op =>
<Operations sym={op.sym} wrd={op.wrd} handleClick={this.handleDisplay}/>)}
<button id='decimal'>.</button>
<button id='clear' onClick={this.clearDisplay}>Clear</button>
</div>
)
}
}
When I press the equals sign I get the same expression back. I have tried passing 'this.props.exp' and this.props.exp.toString() into the eval() function but it is still giving me the same string back without evaluating it.
Apologies, i should specify that expression is based on an array of values created by clicking buttons with 0-9 and the 4 basic expressions. I then pass that array into the eval() function using this.props.exp.join(""). I was using toString() forgeting that it puts commas between all the elements.