Double Click and Click on ReactJS Component

user1261710 picture user1261710 · Feb 18, 2016 · Viewed 17.9k times · Source

I have a ReactJS component that I want to have different behavior on a single click and on a double click.

I read this question: onClick works but onDoubleClick is ignored on React component

<Component
    onClick={this.onSingleClick}
    onDoubleClick={this.onDoubleClick} />

And I tried it myself and it appears as though you cannot register both single click and double click on a ReactJS component.

I'm not sure of a good solution to this problem. I don't want to use a timer because I'm going to have 8 of these single components on my page.

Would it be a good solution to have another inner component inside this one to deal with the double click situation?

Edit:

I tried this approach but it doesn't work in the render function.

render (

    let props = {};

    if (doubleClick) {
        props.onDoubleClick = function
    } else {
        props.onClick = function
    }
    <Component
        {...props} />
);

Answer

Philipp Wrann picture Philipp Wrann · Mar 15, 2018

I know this is an old question and i only shoot into the dark (did not test the code but i am sure enough it should work) but maybe this is of help to someone.

render() {
    let clicks = [];
    let timeout;

    function singleClick(event) {
        alert("single click");
    }

    function doubleClick(event) {
        alert("doubleClick");
    }

    function clickHandler(event) {
        event.preventDefault();
        clicks.push(new Date().getTime());
        window.clearTimeout(timeout);
        timeout = window.setTimeout(() => {
            if (clicks.length > 1 && clicks[clicks.length - 1] - clicks[clicks.length - 2] < 250) {
                doubleClick(event.target);
            } else {
                singleClick(event.target);
            }
        }, 250);
    }

    return (
        <a onClick={clickHandler}>
            click me
        </a>
    );
}

I am going to test this soon and in case update or delete this answer.

The downside is without a doubt, that we have a defined "double-click speed" of 250ms, which the user needs to accomplish, so it is not a pretty solution and may prevent some persons from being able to use the double click.

Of course the single click does only work with a delay of 250ms but its not possible to do it otherwise, you have to wait for the doubleClick somehow...