0

new there. I started learning React and I have a code problem - I can't figure it out. I tried to find the problem here:

https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Functions/Arrow_functions

I perform a bind - and send the function to another component.

{this.state.array.map((char, index) => <CharComponent style={mystyle} character={char} click={(index) => this.deleteHandler(index)} key={index}></CharComponent>)}

deleteHandler = (index) => {
    let copyArray = [...this.state.array];
    console.log('copyArray: ' + copyArray);
    copyArray.splice(index, 1);
    console.log('copyArray: ' + copyArray);
    this.setState({ length: copyArray.length, string: copyArray.join(''), array: copyArray });
  }

I can not get the index - it shows me that it is an object and not a number.

I did a bind - I sent the index as a parameter - and then called it in the function

Why should the brackets be empty? click={(index) => this.deleteHandler(index)

2
  • arrow functions cannot be bind. Use "normal" function if you want to bind it Commented Aug 22, 2020 at 9:04
  • 1
    Delete the index in parentheses, in click Commented Aug 22, 2020 at 9:04

1 Answer 1

1

Just remove the index from the parameters of click(), because when you perform a click it gives us an event object and you are actually passing the event object instead of index. That's why is not getting actual index value from map function.

See the following code for example:

{this.state.array.map((char, index) => <CharComponent style={mystyle} character={char} click={() => this.deleteHandler(index)} key={index}></CharComponent>)}

And for your question, Why should the brackets be empty? As mentioned above when we perform a click gives us a javascript Event object in return.

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

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.