0

I try to add many chips (http://react-toolbox.com/#/components/chip) but I really fail with React...

The exemples in the link only show a single deletable chip. As long as there is a single Deletable Chip, it works, but I can't make it works with more chips.

Here's my code :

import React, { PropTypes } from 'react';
import Chip from 'react-toolbox/lib/chip';

var Chiplist = [
    {'id': 1, 'title': 'Keyword 1'},
    {'id': 2, 'title': 'Keyword 2'},
    {'id': 3, 'title': 'Keyword 3'},
    {'id': 4, 'title': 'Keyword 4'}
 ];

class ChipsList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {deleted : {1: false, 2: false, 3: false, 4: false}};
    /*for(i = 0; i < Chiplist.length; $i++){
    state.deleted.i = false;
    }*/
  }


 /* for(i = 0; i < Chiplist.length; $i++){
    state.deleted.i = false;
  }*/

  handleDeleteClick(index) {
    /*this.setState({
      deleted : {1: false, 2: true, 3: false, 4: false}
    });
    console.log(this);*/
    console.log(index);
  };

  render () {
    const mychips = Chiplist.map((chip, index) =>
      this.state.deleted[index] ? null : ( <Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>{chip.title}</Chip> )
    );
    return (
      <div className="chips-list">
        { mychips }
      </div>
    );
  }
}

export default ChipsList;

Why, when I want to pass the index value to the function, the function is called all the time, I don't know why...

Elie Faës
  • 3,215
  • 1
  • 25
  • 41
Spas
  • 1
  • 1

1 Answers1

0

Because you're calling the function:

<Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>

The correct way to pass a function is by not invoking it, ie:

<Chip deletable onDeleteClick={this.handleDeleteClick}>

However, since you need the index, you'll need to save that somehow. Enter closures. What you need to do is have a function that returns a function, like this:

handleDeleteClick(index) {
  return () => {
    console.log(index);
  }
};

Then, you can create a chip using your original method:

<Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>
taylorc93
  • 3,676
  • 2
  • 20
  • 34
  • Thx for the answer, but when I use your handleDeleteClick function, it logs nothing. And when I console.log(index); before the return, the index variable is a weird object, but not the int I expect... – Spas Jun 07 '17 at 15:23
  • Updated my answer a bit. If it's still failing, can you update your question with what your component looks like now? – taylorc93 Jun 07 '17 at 15:48
  • @Spas Glad that this resolved your issue. Mind accepting the answer? – taylorc93 Jun 07 '17 at 17:49