O
O
Olga2018-04-17 18:58:55
React
Olga, 2018-04-17 18:58:55

How to determine the index of the element that was clicked?

this.state = {
  selectCard: {id: null, select: false}
};

A block with cards is rendered on the page, inside each card there is a button. It is necessary to determine which of the cards was clicked and pass the serial number of this card to selectCard and change the value of select to true.
Now everything looks like this:
a function that should determine the index of the card that was clicked
handleOnClick(){
    let cards = document.querySelectorAll('#fabricCard'); //собираем массив все карточек
    cards.forEach((card, i) => card.addEventListener('click', () => {
      this.saveData(i);
    }));
  }

function that changes selectCard:
saveData(i){
    this.setState({
      selectCard: {
        id: i,
        select: !this.state.selectCard.select
      }
    });
  }

render:
render{
return(
<div className={styles.expand_container}>
  {_mock_.free_fabric.map(card =>
  <FreeFabricCard key={card.id}{...card} amountCard={amountCard} handleClick={this.handleOnClick} choose={selectCard.select}/>
          )}
</div>
)
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Aleksandrovich, 2018-04-17
@melkaya94

render{
return(
<div className={styles.expand_container}>
  {_mock_.free_fabric.map((card,index) =>
  <FreeFabricCard key={card.id}{...card} amountCard={amountCard} handleClick={this.handleOnClick.bind(index)} choose={selectCard.select}/>
          )}
</div>
)
}

handleOnClick(ind){
    console.log("your index",ind)
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question