kermitvomit kermitvomit - 1 year ago 63
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 Source

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() {
    this.state = {
      data: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'],
    this.handleClick = (item) => this.removeItem(item);
  removeItem(item) {
    let data =, i) => i != item);
    this.setState({ data });
  render() {
    return (
      {, i) => <div key={i} onClick={() => this.handleClick(i)}>{item}</div>)}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src=""></script>
<script src=""></script>
<div id="View"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download