0

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

  • either use arrow function or bind this to function – Shubham Agarwal Bhewanewala Aug 02 '18 at 07:38
  • @ShubhamAgarwalBhewanewala did the binding ,that worked .But whenever I define an arrow function it throws some exception. thats why I have defined all the functions with names like addThisNumber (){..} instead of addThisNumber= () =>{..} . Why? Does it have something to do with the version of react i am using ("react": "^16.4.1","react-dom": "^16.4.1") or something else? Thanks – shailesh joshi Aug 02 '18 at 08:53
  • can you post that exception? the version is not the problem m sure – Shubham Agarwal Bhewanewala Aug 02 '18 at 08:54
  • Here it is : App.jsx Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C:/Users/SsJoshi/Desktop/React/App.jsx: Unexpected token (14:10) 12 | } 13 | > 14 | addOne= () =>{ | ^ 15 | this.setState({ 16 | count: this.state.count + 1 17 | }); – shailesh joshi Aug 02 '18 at 09:04

2 Answers2

2

You need to bind your appendThisNumber() to this.

Bind it in your constructor as:

 this.appendThisNumber = this.appendThisNumber.bind(this);
SkrewEverything
  • 2,393
  • 1
  • 19
  • 50
1

You need to bind the function in your class to do so :

  class App extends React.Component {
  constructor(props) {
      super(props);
+     this.appendThisNumber = this.appendThisNumber.bind(this);
      this.state = {
          count: 0,
          numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
          actions: ['=','+','-','*','/','.','C']
      }
  }

See the official doc on "Handling events" for more informations

Julien Deniau
  • 4,880
  • 1
  • 18
  • 22