react passing the parameter to a function that returns an async function

Ayrad

In react how do I pass the identifier of the button that was clicked on to the parent component if my click handler returns an async function?

In the parent:

jumpToItem = async () => {
  const { activeItem } = this.props;
  ...
}

I'm passing to the handler to the child like this:

<ItemSelector activeItem={activeItemIndex} itemsCount={itemsNumber}  onClick={this.jumpToItem} />

In the child component:

return (
  <Item key={index} {...itemProps} onClick={this.props.onClick} />
);

Can I pass the index of the clicked item all the way up to JumpToItem ? Do I need to do something like this?

jumpToItem = async (index) => {
  const { activeItem } = this.props
  // ...do something with index...
}

or do I have to pass the parameter like this:

jumpToItem(index) = async () => {
  const { activeItem } = this.props
  // ...do something with index...
}
Spidy

I think you have confused your syntax here. jumpToItem is not a function that returns an async function. It's just an async function. Functions that return a function typically look like this:

jumpToItem = index => async () => {
  const { activeItem } = this.props;
  // Do something with activeItem or index
  // index is available from lexical scope
};

The component would look like this:

return <ChildComponent onClick={this.jumpToItem(i)} />;

Do you see how I actually invoke jumpToItem when I pass it into onClick? This pattern is used a lot with loops where you want to reuse a handler but need to pass in some piece of data like the name, index, etc... Alternative patterns include placing the data on the node itself and retrieving it through e.target

So that answer to your question is, if you want to pass in extra data, you need an extra function (after the = sign) and the parameters are available through scoping rules. If you don't need extra data because all the data is attached to the target or sent in the callback parameters, then proceed as normal and understand you aren't returning a function the way you have it written now.

I think the new ES6 fat arrows can often confuse even advanced developers. Here's the same thing written in standard ES5 functions.

jumpToItem = function(index) {
  return async function() {
    const { activeItem } = this.props;
    // Do something with activeItem or index
    // index is available from lexical scope
  };
};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related