4

i have an ingredientsArray which is constructed by adding items from a drop down menu after pressing on a button, and then when i try to delete an item using deleteIngredient from this array by pressing on the item it behaves in a strange way and the index always returns -1

import React from 'react';
import { Link } from 'react-router';

export default class Order extends React.Component {

constructor() {
    super()
    this.state = {
      selectedCircle:{},
      cheeseAdd: false,
      ingredient:'',
      ingredientsArray: []
    };
  }

  onSelectIngredient(e){

    this.setState({
      ingredient: e.target.value
    })
  }

addIngredient(){

    this.state.ingredientsArray.push(this.state.ingredient+" ");
    this.forceUpdate();
  }

  deleteIngredient(e) {

  var array = this.state.ingredientsArray;
  var index = array.indexOf(e.target.value);
  console.log(e.target.value);
  array.splice(index, 1);
  this.setState({ingredientsArray: array });
}

  onAddCheese(){

    let add = !this.state.cheeseAdd;
    this.setState({cheeseAdd : add});
  }

  saveAndContinue(e){
    e.preventDefault();
    var pizzaObject = JSON.stringify(this.state.selectedCircle);
    var pizza = pizzaObject.substring(2,4);
    if(this.state.cheeseAdd == true)
    {
        var cheeseChoice = "Yes";
    }
    else{
        var cheeseChoice = "No"
    }
    var data = {
       pizzaSize   : pizza,
       cheese      : cheeseChoice,
       ingredients : [this.state.ingredientsArray]
    }

    this.props.saveValues(data);
    this.props.changeArrowBlack_1();
    this.props.nextCase();
  }

 toggleChoice(name, event) {
     let selected = this.state.selectedCircle;
     selected = {};
     selected[name] = this.state.selectedCircle[name] == "active-circle" ?        "" : "active-circle";
     this.setState({selectedCircle: selected});
  }



  render() {
    const { selected } = this.state;
    const selectedCircle = selected ? "active-circle":"";
    return (
        <div class="container card-layout" id="order-layout">
            <div class="row">

                    <div class="card-panel white">
                      <div class="center">
                        <h5 class="bold">Your Order</h5>
                        <p class="margin-top-30 bold">Choose Pizza size in cm</p>
                        <ul class="margin-top-30">
                            <li ><div onClick={this.toggleChoice.bind(this, "20")} class={"circle-20 hovered-circle " + this.state.selectedCircle["20"]}>20</div></li>
                            <li ><div onClick={this.toggleChoice.bind(this, "30")} class={"circle-30 hovered-circle " + this.state.selectedCircle["30"]}>30</div></li>
                            <li ><div onClick={this.toggleChoice.bind(this, "40")} class={"circle-40 hovered-circle " + this.state.selectedCircle["40"]}>40</div></li>
                          </ul> 
                           <p class="bold margin-top-20">Ingredients:</p>
                        <div class="row">
                            <select class="browser-default col s5 offset-s3" defaultValue="0" onChange={this.onSelectIngredient.bind(this)}>
                              <option value="0" disabled>Choose Ingredients</option>
                              <option value="Tomato sauce">Tomato sauce</option>
                              <option value="Mozarella">Mozarella</option>
                              <option value="Mushrooms">Mushrooms</option>
                      <option value="Cheese">Cheese</option>
                      <option value="Salami">Salami</option>
                            </select>
                            <i onClick={this.addIngredient.bind(this)} class="material-icons medium col s1 add-ingredient">add_box</i>
                          </div>
                  <div class="row ingredients-row">
                    {this.state.ingredientsArray.map((item, index) => <span class="col s3" key={index} >{item}<img src="/img/icons/cancel_small.png" onClick={this.deleteIngredient.bind(this)} /></span> )}
                  </div>  
                            <p class="bold margin-top-30">Cheese rand ?</p>
                            <div class="switch margin-top-20">
                                <label>no
                                <input ref="cheeseRand" type="checkbox" checked={this.state.cheeseAdd} onChange={this.onAddCheese.bind(this)}  />
                                <span class="lever"></span>
                                yes</label>
                            </div>
                            <div class="divider margin-top-30"></div>
                            <button onClick={this.saveAndContinue.bind(this)} class="waves-effect waves-light btn red-button margin-top-20"><i class="material-icons right">arrow_forward</i>Next</button>
                     </div>
                   </div>
            </div>
        </div>
    );
  }
}
Jickson
  • 5,133
  • 2
  • 27
  • 38
user3209048
  • 91
  • 1
  • 6
  • Can you show a sample array? – Rajesh Oct 08 '16 at 06:35
  • @Rajesh a sample array would be for example ingredientsArray["Mushrooms ", "tomatoes ", "cheese "], i get values from the dropdown as shown in the code, and push them to the array and each array item gets populated to the dom as a span and i have an onclick funcion on that span that should delete that array item, but its not working properly – user3209048 Oct 08 '16 at 06:40
  • Have you tried `.trim()`? `e.target.value.trim()`? – Rajesh Oct 08 '16 at 06:42
  • @Rajesh yes, if you use trim then it stops working completely, without trim it deletes, but the wrong item, and index always return -1 – user3209048 Oct 08 '16 at 06:52
  • Please provide [mcve]. –  Oct 08 '16 at 14:21

1 Answers1

3

You are not passing the index of the item to deleteIngredient(). In your map method you can do:

onClick={this.deleteIngredient.bind(this, index)}

And then in deleteIngredient()

You can access it like so:

deleteIngredient(index) {
   console.log(index)
   ...
 }

Also, you are updating the state incorrectly, here is a quick fix:

  deleteIngredient(index) {
    console.log(index);
    var array = this.state.ingredientsArray.slice();
    array.splice(index, 1);
    this.setState({ingredientsArray: array });
  }

Or, using the filter method:

  deleteIngredient(index) {
    this.setState({
      ingredientsArray: this.state.ingredientsArray.filter((item, i) => i !== index)
    });
  }

Or, using the ES6 spread operator:

 deleteIngredient(index) {
    this.setState({
      ingredientsArray: [
        ...this.state.ingredientsArray.slice(0, index),
        ...this.state.ingredientsArray.slice(index + 1)
      ]
    });
  }

Here is a demo: http://codepen.io/PiotrBerebecki/pen/bwLyOJ

Piotr Berebecki
  • 7,428
  • 4
  • 33
  • 42
  • 1
    works perfectly, thank you very much, i am still a javascript and react novice, thank for sharing and making me better! – user3209048 Oct 08 '16 at 07:34
  • 1
    Glad I could help, I've also added the spread operator way of removing an item from the array. – Piotr Berebecki Oct 08 '16 at 07:37
  • You shouldn't be using `.bind` syntax in JSX, instead, create a component, where you pass the `deleteIngredient` callback and index and then call it from within this component. – kudlajz Oct 08 '16 at 13:55
  • Great tip @kudlajz. Here is an example of how we can do this: http://stackoverflow.com/a/38908620/4186037 – Piotr Berebecki Oct 08 '16 at 14:20