Abdelouahab
Abdelouahab

Reputation: 7539

Can't pass a function to props

I begin with React and it seems that props only accepts values and not functions? I get an error while I try to do this:

var Hello = React.createClass({
    render: function() {
        return (
            <div>
                hey there! {this.props.x}
            </div>
        );
    },
    calcul: function(a, b){
        return a*b
    }
});

React.render(
    <Hello x={this.calcul(5, 6)}/>,
    document.getElementById('content')
)

I get this Uncaught TypeError: this.calcul is not a function

But when I use x={this.calcul} it fails silently.

Upvotes: 3

Views: 524

Answers (2)

David Castro
David Castro

Reputation: 738

I think the "React" way could be something like this

  var Calculator = React.createClass({
    render: function() {
        return (
            <div>
                hey there! {this.calcul(this.props.x, this.props.y)}
            </div>
        );
    },
    calcul: function(a, b){
        return a*b;
    }
});

React.render(
    <Calculator x={5} y={6}/>,
    document.getElementById('content')
);

But there are a LOT of ways of doing this.

Upvotes: 1

franky
franky

Reputation: 1333

this.calcul doesn't exist because this is bound to the global context in this case. If you wanted to pass the result of calcul as a prop:

function calcul(a, b) {
  return a*b;
}

var Hello = React.createClass({
  render: function() {
    return (
      <div>
          hey there! {this.props.x}
      </div>
    );
  },
  calcul: calcul
});

React.render(
  <Hello x={calcul(5, 6)} />,
  document.getElementById('content')
);

So here 30 would be passed as prop x and your component will have the calcul function.

Upvotes: 2

Related Questions