1

I am trying to render React components using loop, Basically its link tag having on click function with value.

<p><a href="#" key={i} onClick={() => this.decreaseCount(i)} >delete</a></p>

where i is the index of the for loop. The problem is, instead of getting i's value inside this.decreaseCount(i) I am getting length of array. However I am getting correct index with key={i}

Need help!

1 Answer 1

2

That should work, try to use this (another way):

<p><a href="#" key={i} onClick={this.decreaseCount.bind(this,i)} >delete</a></p>

Check this example, you way will also work:

class App extends React.Component{
   
   a(i){
     console.log(i);
   }
   
   render(){
     return (
        <div>
           {
               [1,2,3].map(i => <p onClick={ () => this.a(i)} > {i} </p>)
           }
        </div>
     )
   }
}

ReactDOM.render(<App/>,document.getElementById('app'))
<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='app'/>

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, Working! Thanks for your help!

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.