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.