kermitvomit kermitvomit - 25 days ago 7
React JSX Question

Using state and button to remove an element from a list

I have a list created like so:

return (this.state.limit).fill().map((_,index) => {
return (
<div key={`${index}`}> Item </div>
)
)


How can I create a button that let's me remove a specific div element as well as reduce the state limit?

Answer

In React, you will have to bind almost everything to data. In your example, all those items should be represented by some underlying data. Here's a very basic example showing this:

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      data: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'],
    };
    this.handleClick = (item) => this.removeItem(item);
  }
  removeItem(item) {
    let data = this.state.data.filter((_, i) => i != item);
    this.setState({ data });
  }
  render() {
    return (
    <div>
      {this.state.data.map((item, i) => <div key={i} onClick={() => this.handleClick(i)}>{item}</div>)}
    </div>
    );
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

Comments