1

I am using react.js in my project and I have component hierarchy like this.

RootComponent
|- Child1
|  |- itemA1
|  |- itemA2
|   - ...
 - Child2
   |- itemB1
   |- itemB2
    _ ...

I have all the state in RootComponent, which is:

  • array of itemA elements
  • array of itemB elements
  • index of currently selected itemA
  • index of currently selected itemB

I want to change the currently selected item by clicking on an item, so I created a property in my RootComponent:

changeCurrentItemA: function(item) {
    console.log("check, if the function was called");
    //do something with state
}

I passed it down to Child1:

<Child1 items={this.state.data.itemsA} changeCurrentItemA={this.changeCurrentItemA} />

In the child compomnent, I take the function from props:

var changeCurrentItemA = this.props.changeCurrentItemA;

and I wanted to render it like this:

<li onClick={changeCurrentItemA(item)} />

This howerver immediately evaluates the function, so during rendering, it gets evaluated n times and nothing happens, when I click it.

How can I tell react to run function with variable item passed to it after user clicks.

I saw similar question here: React.js how to pass callbacks to child components? but the function there has no arguments.

EDIT: It is not a duplicate of questions about bind, because react hijacks default bind behaviour allowing only binding on components.

Community
  • 1
  • 1
tkowal
  • 9,129
  • 1
  • 27
  • 51
  • 1
    See here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – elclanrs Mar 30 '15 at 10:07
  • Thanks, but I still have a problem. I could call `bind` in the scope of `Child1` component to provide `item` as an argument, however, I would also have to provide `this`. Should I also pass "this value of `RootComponent`" down to the `Child1` to be able to call `bind` in `Child1` or is there better solution? – tkowal Mar 30 '15 at 10:16
  • 2
    Try `onClick={this.props.changeCurrentItemA.bind(this, item)}` – elclanrs Mar 30 '15 at 10:32
  • Thanks, it worked. I have to refresh my understanding on this and bind in javascript. – tkowal Mar 30 '15 at 10:43

0 Answers0