lqsdwtxkzlqafpvluq
lqsdwtxkzlqafpvluq

Reputation: 85

React. List -> ListItem click and send params

Cant understand how i can create click by item in List and sent params. For example if i using this code

    <List>
         {filesList ? (
           filesList.map((item, index) => (
            <ListItem key={index} button onClick={this.setCurrentUrl(index)}>
               <ListItemIcon>
                   <InsertDriveFile/>
               </ListItemIcon>
               <ListItemText primary={item.name} />
            </ListItem>
        ))
    ) : (
            <ListItem>There are no attachement files</ListItem>)}
            <ListItem/>
      </List>

method setCurrentUrl:

setCurrentUrl(index) {
        console.log(index);
    }

i will have output all items in the console when my page is loaded. Why? But if i make something like this:

<ListItem key={index} button onClick={this.setCurrentUrl} value={index}>

and

setCurrentUrl(event) {
        console.log(event);
    }

then console.log(event); will be call only when i click on item in the list. But in this way i dont know how send params to setCurrentUrl

Upvotes: 0

Views: 185

Answers (2)

Saad Awan
Saad Awan

Reputation: 96

The way you are using

 <ListItem key={index} button onClick={this.setCurrentUrl(index)}>

it is problematic as the function setCurrentUrl will be called as soon as the component is rendered. To make a call to function only when onClick event is triggered, you need to make use of callbacks.

<ListItem key={index} button onClick={() => this.setCurrentUrl(index)}>

Using callback will not call the function while the component is being rendered and would only call the function when the onClick event is triggered.

Upvotes: 2

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

The reason it happens because you are calling the function. The function will execute immediately after the component is rendered .

 <ListItem key={index} button onClick={this.setCurrentUrl(index)}>

Instead what you should have done is

<ListItem key={index} button onClick={() => this.setCurrentUrl(index)}>

What this will do is , it will assign the function to the onClick handler and will be invoked only when you click the button.

Upvotes: 1

Related Questions