0

I'm attempting to recreate a calculator I made in Angular using React. I found recreating the html was not too difficult, but I'm having an issue with binding onclick events inside a looped Element.

Here's the element I want to recreate:

class Button extends React.Component {
  render(){
     return <div onClick={this.props.func} className="calc-button">{this.props.value}</div>;
  }
}

Here's where I want it to loop and bind a function to the button.

class OperationsBox extends React.Component {
  constructor(props){
    super(props);
    this.state = objButton;
    this.numClick = this.numClick.bind(this);}
  numClick(){
    console.log("5") 
  }

  render(){
    var rows = [];
    this.state.button.forEach(function(button,index){
    var row  = button.map(function(obj, index2)
    {
       if(index===4){
          return <div className="calc-button clear">{obj.value}</div>;
    }
    return(<Button 
            func={this.numClick.bind(this, index2)} 
            value={obj.value}
            />);
            }.bind(this))
     rows.push(row)})

return <div className="operations-box">
   <div className="calc-row">{rows[0]}</div>
   <div className="calc-row">{rows[1]}</div>
   <div className="calc-row">{rows[2]}</div>
   <div className="calc-row">{rows[3]}</div>
   <div className="calc-row">{rows[4]}</div>
   </div>;
  }
}

It constantly says the numClick is undefined.

Here's the link to my React Calc

http://codepen.io/awronka/pen/XmyQxB?editors=001

Here's my link to my working Angular Calc

http://codepen.io/awronka/pen/yYeLdp

Mifune
  • 128
  • 8
  • 1
    Try to fix your indentation. It then should be pretty obvious that you've bound only one of your two loop callbacks. With ES6, you should switch to arrow functions anyway. – Bergi Nov 15 '15 at 21:18
  • Objbutton is an object that contains a list of values that I want displayed on the button objects. – Mifune Nov 15 '15 at 21:35
  • Bergi, can you further explain that I've only bound one of the loop callbacks. I'm not completely clear on that – Mifune Nov 15 '15 at 21:36
  • You have `.forEach` and `.map`, but you only bind the callback passed to `.map`. What do you expect `this` inside the `.forEach` callback to be? – Felix Kling Nov 16 '15 at 00:47

0 Answers0