I was trying to build a simple calculator application to get started with React. I was trying to call a function in root component from the child one so as to access the current state. I was able to call the function but I can not access the state as i want update the state . Below is my code :
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
actions: ['=','+','-','*','/','.','C']
}
}
appendThisNumber(number,oldcount){
let newCount=parseInt(oldcount.toString()+number.toString());
console.log('New number '+newCount);
//below code errors out
this.setState({
count:newCount
});
};
performThisAction(action, oldcount){
// stuff to do
};
render() {
return (
<div>
<CounterDiv countNow={this.state.count} />
<div>
{this.state.numbers.map((n) => <NumButton NumValue={n} countNow={this.state.count} onClickFunction={this.appendThisNumber}/>)}
</div>
<div>
{this.state.actions.map((a) => <ActionButtons actionItem={a} countNow={this.state.count} onClickFunction={this.performThisAction}/>)}
</div>
</div>
);
}
}
class CounterDiv extends React.Component {
render() {
return (
<div>
<input type='text' readOnly value={this.props.countNow} />
</div>
);
}
}
class NumButton extends React.Component {
handleClick(){
this.props.onClickFunction(this.props.NumValue,this.props.countNow);
}
render() {
return (
<button onClick={()=>this.handleClick()} value={this.props.NumValue}>{this.props.NumValue}</button>
);
}
}
class ActionButtons extends React.Component{
handleClick(){
this.props.onClickFunction(this.props.actionItem,this.props.countNow);
}
render() {
return (
<button onClick={()=>this.handleClick()} value={this.props.actionItem} label={this.props.actionItem}>{this.props.actionItem}</button>
);
}
}
export default App;
What am I doing wrong or do I need to use some data binding framework for it ? Thanks in advance