asparism
asparism

Reputation: 614

React components rendering incorrectly

I have a react project, a recipe box, which includes the ability to open a recipe and add/delete ingredients. Here is a fiddle. You can click the recipe name to open the recipe. There is an edit button which reveals the delete button and gives the option to change the name of the ingredients. When the 'delete ingredient' button is pressed, the last ingredient appears to always be deleted, regardless of which ingredient is selected, but when the 'done' button is clicked and the editable input boxes change back to text, the correct change is shown, the proper ingredient deleted and the last ingredient remains. Though this works functionally, it's obviously not very UI friendly, and I wondered why this was happening. Any help would be great.

jsFiddle

class Input extends React.Component {
  render() {
   const array = this.props.update;
   let booleanButton = null;
   if (this.props.ingr) {
////////////////////////////
// here is the button's JSX
    booleanButton = <button onClick=
    {this.props.handleDeleteIngredient.bind(this, array)}>delete 
    ingredient</button>;
///////////////////////////
   }
 return (<div><form><input type="text" defaultValue={this.props.text} 
   onChange={this.props.onChange.bind(this, array)} /></form>{booleanButton}
  </div>)
  }
}

And the handler:

handleDeleteIngredient(data, e ) {
  var key = data[2];
  var ingrs = this.state.ingrs;
  ingrs.splice(key, 1);
  this.setState({ingrs:ingrs});
}

Upvotes: 1

Views: 876

Answers (1)

Zhang Bruce
Zhang Bruce

Reputation: 914

Your description is quiet confusing, and according the your fiddle code I think your problem is caused by not setting a good key for your list Item.
from what it looks in this line, you don't have a key={ingrs[i]} props, try set it to id see it will work, but making ingrediant name as key is probably not a good idea, try to give an actual id.

ingrList.push(<Input key={ingrs[i]} handleDeleteIngredient={this.handleDeleteIngredient.bind(this)} id={id}  update={[this.props.objectIndex, "ingrs", i]} onChange={this.onInputChangeIng.bind(this)} text={ingrs[i]} />);

Upvotes: 3

Related Questions