0

I'm learning React and am building a simple todo list. I have this object in my initialState

 getInitialState:function(){
    return {
        items: [
            {
                text:"Buy Fish",
                key: "1",
                done: 0
            }
            ]
        }
 },

My TodoList component has this map function

var listItem = this.props.items.map((item, index)=>{
        return <li key={item.key}> <input type="checkbox" onChange={(e)=>{this.props.onChange(item.key, e)}} /> <span onClick={()=>{this.props.editItem(item.text)}}>{item.text}</span> <button onClick={()=>this.props.removeItem(item.key)}>x</button> </li>
    });

Now I want to click on the checkbox and change the state of the property done to 1.

The onChange prop is leading to a function

  itemDone:function(index, e){
  var myArray = this.state.items;
  var a = e.target.checked;
  console.log(index);
},

What is the correct way to change the value from 0 to 1 to that specific item?

0

2 Answers 2

1

You can pass the index to your onChange method.

var listItem = this.props.items.map((item,index)=>{
            return <li key={item.key}> <input type="checkbox" onChange={(e)=>this.props.onChange(index,e)} /> <span onClick={()=>{this.props.editItem(item.text)}}>{item.text}</span> <button onClick={()=>this.props.removeItem(item.key)}>x</button> </li>
        });

and get specific items with and index:

itemDone:function(index,e){
    var myArray = this.state.items;
    var a = e.target.checked;
    console.log('item': this.state.items[index]);
 },
Sign up to request clarification or add additional context in comments.

Comments

0

Pass the index and then edit the same object. Also make use of spread operator to create a new object instance of the item array otherwise, myArray will refer to the immutable object state item itself.

var listItem = this.props.items.map((item, index)=>{
            return <li key={item.key}> <input type="checkbox" onChange={()=>this.props.onChange(index)} /> <span onClick={()=>{this.props.editItem(item.text)}}>{item.text}</span> <button onClick={()=>this.props.removeItem(item.key)}>x</button> </li>
        });


itemDone:function(index){
    var myArray = [...this.state.items];
    if(myArray[index].done == 0) {
          myArray[index].done = 1; 
    } else {
          myArray[index].done = 0; 
     }
    this.setState({items: myArray})
 },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.