Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove an item from a list with a click event in ReactJS?

var FilterList = React.createClass({
  remove: function(item){

    this.props.items = this.props.items.filter(function(itm){
      return item.id !== itm.id;
    });

    return false;
  },
  render: function() {
    var createItem = function(item) {
      return (
        <li>
          <span>{item}</span>
          <a href data-id="{item.id}" class="remove-filter" onClick={this.remove.bind(item)}>remove</a>
        </li>

      );
    };
    return <ul>{this.props.items.map(createItem.bind(this))}</ul>;
  }
});
var FilterApp = React.createClass({
  getInitialState: function() {
    return {items: [], item: {
      id: 0,
      type: null
    }};
  },
  onChangeType: function(e){
    this.setState({
      item: {
        id: this.state.items[this.state.items.length],
        type: e.target.value
      }
    });
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var nextItems = this.state.items.concat([this.state.item]);
    var item = {};
    this.setState({items: nextItems, item: {}});
  },
  render: function() {
    return (
      <div>
        <h3>Filters</h3>
        <FilterList items={this.state.items} />

        <form className="filter" onSubmit={this.handleSubmit}>
          <fieldset>
            <legend>Filter</legend>
            <div className="form-grp">
              <select name="type" onChange={this.onChangeType}>
                <option>foo</option>
                <option>bar</option>
                <option>baz</option>
              </select>
            </div>
          </fieldset>
          <div className="actions">
            <button>{'Add #' + (this.state.items.length + 1)}</button>
          </div>
        </form>
      </div>
    );
  }
});

React.render(<FilterApp />, document.body);

I cannot seem to wrap my head around how to remove an item from the list. Probably making a ton of other bad design decisions here too, newbs.

like image 644
chovy Avatar asked Jan 07 '15 10:01

chovy


People also ask

How do I remove an item from Click React?

On the click event handler, pass data with random id to the addItem method to add a new list item on clicking the Add Item button. Bind the click handler to the delete icon created in step 1. Within the click event, remove the list item by passing the delete icon list item to removeItem method.

How do I remove an item from a React list?

To delete an item from list with React and JavaScript, we can use some array methods. to create the items state with useState . Then we define the deleteItem function that takes the index of the item to delete and returns a function that calls setItems with (items) => items. filter((_, i) => i !==

How do I remove an array from Click React?

To remove an element from a state array in React: Use the filter() method to iterate over the array. On each iteration, check if a condition is met. Set the state to the new array that the filter method returned.

How do I remove one element from an array in React?

To remove an element from an array of objects in React: Use the filter() method to iterate over the array. On each iteration check if a certain condition is met. The filter method returns an array containing only the elements that satisfy the condition.


2 Answers

Props on components are immutable, meaning you cannot modify them directly. In your above example if the FilterList component wants to remove an item, it would need to call a callback from the parent component.

A simplified example of this.

FilterApp passes a remove function to FilterList that is called on the onClick event. This will remove an item from the parent, update the state, then cause FilterList to re-render with the new content.

Hope this helps.

like image 156
Ashley 'CptLemming' Wilson Avatar answered Oct 05 '22 12:10

Ashley 'CptLemming' Wilson


Something like the below should work. Let your root component manage state.

var FilterList = React.createClass({
  render: function() {
    var createItem = function(item) {
      return (
        <li>
          <span>{item}</span>
          <a href data-id="{item.id}" class="remove-filter" onClick={this.props.remove.bind(item)}>remove</a>
        </li>

      );
    };
    return <ul>{this.props.items.map(createItem.bind(this))}</ul>;
  }
});

var FilterApp = React.createClass({
  getInitialState: function() {
    return {items: [], item: {
      id: 0,
      type: null
    }};
  },
  onChangeType: function(e){
    this.setState({
      item: {
        id: this.state.items[this.state.items.length],
        type: e.target.value
      }
    });
  },
  remove: function(item, ev){
    ev.preventDefault();

    var items = this.state.items.filter(function(itm){
      return item.id !== itm.id;
    });

    this.setState({ items: items });
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var nextItems = this.state.items.concat([this.state.item]);
    var item = {};
    this.setState({items: nextItems, item: {}});
  },
  render: function() {
    return (
      <div>
        <h3>Filters</h3>
        <FilterList remove={this.remove} items={this.state.items} />

        <form className="filter" onSubmit={this.handleSubmit}>
          <fieldset>
            <legend>Filter</legend>
            <div className="form-grp">
              <select name="type" onChange={this.onChangeType}>
                <option>foo</option>
                <option>bar</option>
                <option>baz</option>
              </select>
            </div>
          </fieldset>
          <div className="actions">
            <button>{'Add #' + (this.state.items.length + 1)}</button>
          </div>
        </form>
      </div>
    );
  }
});

React.render(<FilterApp />, document.body);
like image 35
TYRONEMICHAEL Avatar answered Oct 05 '22 11:10

TYRONEMICHAEL