user1189352
user1189352

Reputation: 3885

React, getting index of list when clicked

I'm trying to follow the examples that are coming up here on Stack Overflow and I can't get it to work. It works just fine if I remove everything that says "index" though. It passes in the "page" just fine. Can someone point me in the correct decision please thank you.

My Click function

handleOnClick(page, index) {
    console.log(page);  //page is correct
    console.log(index); //undefined

}

My Render

let self = this;

    playlistList[pos].list.map(function(page, index)

    {if (page.selected) {
      return (
        <tr key={page.id} onClick={() => self.handleOnClick(page, index)}>
          <td>{page.name}</td>
          <td>{page.subComposition.name}</td>
        </tr>
      );}
    }

Upvotes: 0

Views: 1816

Answers (3)

A. Horst
A. Horst

Reputation: 88

Are you sure that your function handleOnClick it's correct? I think the parameters are wrong.

When you call the function you pass handleOnClick(page, index), and in the method the parameters are handleOnClick(index, page)

Upvotes: 1

A. Horst
A. Horst

Reputation: 88

You have to pass the parameters name in the arrow function parentesis, and it's value through the function parentesis.

Like:

onClick={(page, index) => self.handleOnClick(page, index)}

Upvotes: 2

Mike Hughes III
Mike Hughes III

Reputation: 46

You're probably better off making a component that handles creating the tr. Then creating the function in that component, then running the function using the props passed down.

Unless you're going to need to change the state, then pass the function down to the component to be used.

Upvotes: 2

Related Questions