0

I am trying to implement List in material-ui. And i am trying to display randomly generated array of elements, they are being displayed with scrollbar list as i want. But i want to select that particular List Item which is the issue as i m unable to select it, even by using on click. So can anyone help me in this. Here is my code:

var MuiListElement = React.createClass(
  {
    handleClick() {
        console.log("secondList clicked")
    },
    render()
    {
      let faker = require('faker')
      let myItems = []
      for(let i = 0; i < 5000; i++)
      {
      let name = faker.Name.findName()
      myItems.push(<ListItem onClick={this.handleClick()} key={i.toString()}>{name}</ListItem>)   
      }
    return(
      <div style={{width:'400px'}}>
      <Paper style={{maxHeight: 200, overflow: 'auto'}}>
      <List selectable='true'>
          {myItems}
      </List>
</Paper>
      </div>

    )
    }
  }
)
Taran
  • 3
  • 4

1 Answers1

0

this.handleClick() calls handleClick function during your render, you should call it when the user clicks the list item. You wan't to pass the function to onClick, not call the function.

myItems.push(
  <ListItem 
    onClick={this.handleClick}   //pass function, don't call function
    key={i}>  //note: you can pass key as number
    {name}
  </ListItem>)

Now let me predict the future, you would like to know what item was clicked. You can use bind.

myItems.push(
  <ListItem 
    onClick={this.handleClick.bind(this, i)}   //bind returns a function 
    key={i}>
    {name}
  </ListItem>)

now you know what was passed

handleClick(i) {
    console.log("secondList clicked", i)
},

However, every time you render, you are creating a new function and will slightly degrade performance.
See this discussion, React js onClick can't pass value to method

Let me know if you don't understand.

Mke Spa Guy
  • 793
  • 4
  • 13
  • Thanks for your help! But i want the ListItem to trigger an event when i click it. Output is displayed on console, but i want to select that particular listitem so that it fires some action when i click it. I hope you are getting my point, I appreciate your help. – Taran Aug 18 '17 at 15:02
  • Ummmmm, yea I get your point. Actually that is the exact answer I just gave you. Is there some part you don't understand? I will gladly help. If you do appreciate my help, consider up-voting my answer and marking it as complete once you have your answer. – Mke Spa Guy Aug 18 '17 at 19:37
  • Yeah thanks. But i am saying that i want that particular listItem to be highlighted in List array, which is clicked. I get to know about its click only if i check the console or using alert message. – Taran Aug 18 '17 at 19:54
  • Are you familiar with set state? – Mke Spa Guy Aug 21 '17 at 22:14