0

I have the following two components:

class A extends Component {
   _onDelete(id) {
      this.props.deleteItem(id);
   }
   render() {
      return <B onDelete={this._onDelete}/>;
   }
}


class B extends Component {
   const onDelete= {this.props};
   let id = this.props.item.id;
   render() {
     return <div onClick={onDelete}>Hello</div>;
   }
}

I don't want to bind this (component B context) to the function, I only want to pass id to _onDelete.

I tried these approaches:

  1. Arrow function:

     return <div onClick={() => onDelete(id)}>Hello</div>;
    

context in _onDelete changes to B, and I don't have access to this.props.deleteItem anymore.

  1. Passing by event:

    return <div onClick={onDelete} itemId={id}>Hello</div>;
    
    _onDelete(event) {
       this.props.deleteItem(event.target.itemId);
    }
    

event.target.itemId is undefined

How can I pass the itemId to A's function, without binding this to it ?

2 Answers 2

3
class A extends Component {
   _onDelete = (id) => {
      this.props.deleteItem(id);
   }
   render() {
      return <B onDelete={this._onDelete}/>;
   }
}

This way _onDelete will be available with A context. Just call it like this in B

class B extends Component {
   let id = this.props.item.id;
   render() {
     return <div onClick={() => this.props.onDelete(id)}>Hello</div>;
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

the only difference between your code and my 1st approach is that you made the _onDelete an arrow function. How does that fix the issue ?
When writing _onDelete as arrow function , context remains that of A, And it becomes available binded function with context A in component B. When you are passing non-arrow function, context remains undefined , thats why it was creating an issue. Javascript is lexical scoped language and arrow function keeps the context of the outer scope
1

Your syntax is not quite correct, but I guess it's a problem here, not in your actual code. If you don't want to call .bind(this), then you can pass an arrow function to onDelete which calls _onDelete:

<B onDelete={id => this._onDelete(id)}/>

The better solution would be to directly pass this.props.deleteItem, if that's all that _onDelete is calling:

<B onDelete={this.props.deleteItem}/>

In B you'd have to pass a custom function as well:

return <div onClick={() => onDelete(id)}>Hello</div>;

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.