Home > Software design >  Cannot add to list of items in ReactJS
Cannot add to list of items in ReactJS

Time:05-10

Its been a while since I used ReactJS and I need to create a list of items that I can add to and remove. I've added an onClick event to my li to remove it. I also have a button to add new items, these seem to work but the state is not updating.

var new_items = [...Array(1)].map((val, i) => `No Items`);
<ul className="App-list">
   {new_items.map((item, i) => (<li key={`item_${i}`} onItemClick={onItemClick(i)}>{ item }</li>))}
</ul> 

the onClick function is here

function onItemClick(num) {
  this.setState({
     new_items: this.state.new_items.concat('new value')
  })
}

I just need to either delete a line from the List or Add depending on status but even though it runs it does not update the state. Can someone give me either a batter way of updating a list of rows dynamically or tell me what I'm doing wrong.

CodePudding user response:

Since you are using Class Component you have to call the method with the context of class

onItemClick={this.onItemClick(i)}

CodePudding user response:

You need to add a constructor as follows:

class MyClassName {
    constructor(props) {
        super(props);
        this.state = {
            new_items: [] // or null or any other initial value depending on your use case
        }
        this.onItemClick = this.onItemClick.bind(this);
    }
    function onItemClick(num){ ... }
}

Then while calling the onClick function you call it as follows:

onItemClick={this.onItemClick(i)}

Also, if you are using the generic onClick functionality, you would have to change onItemClick to onClick:

<li key={`item_${i}`} onClick={()=>this.onItemClick(i)}>

Since you are not using the event information from the click, you have to add an anonymous function that calls your desired onClick handler. Hence the ()=>this.onItemClick(i)

  • Related