Search code examples
reactjsevent-handling

react-sortable-hoc: Handling of click event on list item


This question is about https://github.com/clauderic/react-sortable-hoc. I am pretty new to React, so I find the following a bit irritating. Go to https://jsfiddle.net/7tb7jkz5/. Notice line 4

const SortableItem = SortableElement(({value}) => <li className="SortableItem" onClick={console.debug(value)}>{value}</li>);

When you run the code, the console will log "Item 0" to "Item 99". A click on an item will log the same, but three times. Why does this happen? And is this really necessary or more like a bug?

I expected a behavior similar to an ordinary DOM, so the click event would bubble up from the clicked item and could be caught along the way through its ancestors. The observed behavior looks to me like the click event would be sent down by the list to each list item three times.

Update: Well, this is actually as clear as crystal, thanks for pointing this out, Shubham. I did not just specify a reference, but an actual call to console.debug, which was executed every time the expression was evaluated. Common mistake.

Still, this means, each list item is rendered (I guess) three times, when I click one of them. I suspect missing optimization or even useless redrawing.


Solution

  • You need to mention the onClick action as a function. Use () => inside the handler call. Try the below method, it works although has a very slow response

    const SortableItem = SortableElement(({value}) => <li className="SortableItem" onClick={() => console.debug(value)}>{value}</li>);