Warning: Severe React beginner.
I have a class:
export default class ItemsView extends React.Component {
//...
render() {
return (
<div>
<Container>
<Grid container>
<Grid item xs={4}>
<ul style={{listStyleType:"none"}}>
{
this.state.items.map((item) => {
return <li key={item.number} style={{cursor: "pointer"}}><Item onClick={this.handleSelected(item)} value={item.timestamp}/></li>
})
}
</ul>
</Grid>
<Grid item xs={4}>
<ItemDetail item={this.selected} />
</Grid>
</Grid>
</Container>
</div>
)
}
}
handleSelected(item) {
console.log("handle");
this.selected = item;
}
What I want is that when I click on the Item
div, which is rendered dynamically as a list of elements, the details of the item would appear in the ItemDetails
component.
Apart from the fact that probably my design isn't really "React"y, why does the handleSelected
get called when iterating, and not when I click on it?
You are invoking the function rather than passing a function reference to be executed on click. You should either define the handler to return a function or use a lambda / fat arrow function in the click handler
onClick={() => this.handleSelected(item)}
remember, this.handleSelected
is the functions reference. this.handleSelected()
is the return value of an already invoked function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With