1

I have a parent-child relationship for a component I'm trying to setup. I would like to have the parent retain knowledge of the original state of a transaction (a React component) and then determine whether or not to allow the addition of new transactions based on whether or not it is less than that original amount. I do not know how to properly pass data from component to component on click call. My original component is listed below. Please send help!

```

    var transaction = React.createClass({
      getInitialState: function(){
        return {
          transactions: [ { desc: '', val: 0 } ],
          initialTransaction: 10
        }
      },
      render: function(){
        return (
          <div>
           { this.state.transactions.map(this.renderChild) }
            <button onClick={ this.newTransaction }>Add</button>
          </div>
        )
      },
      shouldComponentUpdate: function(nextProps, nextState) {
        console.log(nextState.transactions);
        return nextState.transactions.reduce(function(a, b) {
          return { val: a.val + b.val}
        }) == this.state.initialTransaction
      },
      newTransaction: function(_transaction,x,y){
        this.state.transactions.push(_transaction);

        this.setState({
          transactions: this.state.transactions
        });
        this.forceUpdate();
      },
      renderChild: function(_transaction){
        return (
          <div>
          <input type='text' defaultValue={ _transaction.desc } />
          <input type='text' defaultValue={ _transaction.val }/>
          // TODO: this button should pass a transaction up to the parent component
          </div>
        );
      }
    });
   React.renderComponent(<transaction />, document.getElementById('mount-point'));

```

nobody
  • 7,803
  • 11
  • 56
  • 91

1 Answers1

1

You can pass a callback.

In the parent:

onTransaction: function(transaction) {
  console.log('onTransaction', transaction);
}

And pass it to the child element:

<Transaction onTransaction={this.onTransaction} ... />

In the child you then can call this method via this.props.onTransaction:

renderChild: function(_transaction) {
  ...
  <button onClick={() => this.props.onTransaction(_transaction)} />
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • ok so lets say i dont want to have that button on every child element. i want to have one 'add' button that adds a new transaction to the array and then rerenders the children so i get all the new elements from there. how would i do that? – nobody Dec 03 '15 at 16:47
  • also, what is 'this' referring to in the renderChild call? what is the props element on 'this'? – nobody Dec 03 '15 at 16:48