1

If I have a function that I want to use in a onClick, such as this

*using ReactJS and Semantic-UI

<Table.HeaderCell
  onClick={this.handleSort(items)}
>

where the function returns a reference of a function, such as this

handleSort = (items) => () => {
    console.log('now')
}

then, how can I execute this function outside of the onClick event? What doesn't work:

componentDidMount() {
    this.handleSort.call(items);
    this.handleSort(items);
}
1
  • You got your answer but as far as I know, this is not using the function by its reference. You are currying the function here. So, whenever Table.HeaderCell is rendered this function is recreated every time. If you do this to use the items as an argument, maybe there are better ways. For example, if the items is in your state or it is coming from a prop, you can use it directly instead of currying the function. Commented Oct 3, 2018 at 22:33

2 Answers 2

2

handleSort returns a function, you'll need to invoke it with (), like so:

componentDidMount() {
    this.handleSort(items)();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Not at all, just a simple oversight :)
0

I guess you are trying to execute the inner function that logs 'now' to the console.

As a clarification: this.handleSort(items) returns a anonymous function: () => { console.log('now') }

In order to call it, you may do: this.handleSort(items)() to immediately invoke the inner function.

See:

var handleSort = (items) => () => {
  console.log('now')
}

// holds the inner function part
var innerFunction = handleSort([]);
console.log(innerFunction.toString());

// Equivalent ways to call it directly
innerFunction();
handleSort([])();

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.