when I click on any button what displays is 1 and if i clicked again what I get is error saying that push is not a function .. it seems like index 1 in the button array have been pushed in state.num then the state.num have changed it,s type from array to number so I have 3 questions :
1-why the (1) have been selected to be pushed and not another element in the button array ??I cannot get that
2-why do the type of num has changed??is not it supposed to push the(1) as an array element ?it seems like it exchanged the num array with number 1 .. how did this happened while using push method??
3-what to do to display each element in the buttons array when I click on it??what did I do wrong?
here is my code
class App extends React.Component {
constructor(props){
super(props);
this.state={
num:[],
}
this.handleclick=this.handleclick.bind(this);
}
handleclick (ele){
this.setState({num:this.state.num.push(ele)})
};
render() {
const buttons = ["÷", 1, 2, 3, "*", 4, 5, 6," ", 7, 8, 9, ".", 0, "-"];
return (
<div className="calculation-grid">
<div className="output">
<div className="previous-operand"></div>
<div className="current-operand">{console.log(this.state.num)}</div>
</div>
<button className="span-two">AC</button>
<button>DEL</button>
{buttons.map((ele)=><button onClick={()=>this.handleclick(ele)} key={ele}>{ele}</button>)}
<button className="span-two">=</button>
</div>
);
}
}
export default App;
CodePudding user response:
The issue is Array.prototype.push does not return the updated array (it's the length of the array). You can use the spread operator to push the values like below.
handleclick(ele) {
this.setState({ num: [...this.state.num, ele] });
}
OR (using the callback function)
handleclick(ele) {
this.setState((prevState) => ({
...prevState,
num: [...prevState.num, ele]
}));
}