Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react: why does the onclick get executed even without having clicked?

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?

like image 246
transient_loop Avatar asked Sep 03 '25 04:09

transient_loop


1 Answers

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.

like image 172
Vincenzo Ninni Avatar answered Sep 05 '25 00:09

Vincenzo Ninni