Никита Нягу
Никита Нягу

Reputation: 13

How to dynamically create and delete elements(containing inputs, p-s, buttons), which has their own remove-button

Well, the case is:It is a react application, there is a button, which creates an element with its own remove button. The created element contains inputs, paragraph tags and buttons. The bug i cant remove for several days already is: let's assume deleting the n-th such element, which has a paragraph p {index} /p (index=n) and the input input type="text" {index} /input, the thing is that after removing the element(we cant see it's paragraph anymore) the input's text is replacing the n+1-th input's text, the n+1-th input's text replacing the n+2-th input's text and so on. When n+k is equal to the list size, n+k-th input disappears.

const defaultList=[];
const List = (props) => (
    <ul>
      {props.items.map((item, index) => (
        <li key={index}>
          {item}
          <br />
          <button onClick={() => 
            props.removeItem(index)}>Remove</button>
        </li>
      ))}
    </ul>
  );

export default class Accounts extends React.Component {
    constructor(props) {
        super(props);
        this.addItem = this.addItem.bind(this);
        this.state={
            items: defaultList,
            created:0
        }    
    }

    removeItem(removeIndex) {
        this.setState((state) => ({
          ...state,
          items: this.state.items.filter((item, index) => index !== removeIndex)
        }))
      }

    addItem(){
        const temp = this.state.items;
        temp.push(
        <div>
            <p>{this.state.created}</p>
            <input name="text" type="text" id={"input "+this.state.created}/>
            </div>
        );
        this.setState(() => ({
            items: temp,
            created:++this.state.created
        }))
    }
    render(){
    return(<div>
    <List items={this.state.items} removeItem={this.removeItem.bind(this)} />
    <button  onClick={this.addItem}>Add item</button>
    </div>
    }
}

Well, I cant provide images how it works, cuz this is my first post and I need at least 10 rating to add images :/

Upvotes: 0

Views: 67

Answers (2)

Никита Нягу
Никита Нягу

Reputation: 13

The problem is in using Array.prototype.push() method, which is changing the original array and returns as inline result the new array length. When working with arrays in react state better use methods like map, filter and reduce, because they don’t affect target array and in contrast to push, map returns a new, modified array. Hope it helps and in case you want source of this idea

Upvotes: 0

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

The only problem in this code i see you should write

const temp = [...this.state.items];

in addItem handler, otherwise everything is perfectly ok

Upvotes: 1

Related Questions