Charles
Charles

Reputation: 299

Exclude child components from <div onclick>

I render multiple 'div' which the user can select by clicking on it with a simple onClick:

<div onClick={() => this.handleTrackerCardClick()}>

However the user can also edit a field displayed on the 'div' by clicking on a button. In this case I don't want the 'div onClick' to be called, because obviously the user wants to use the Edit function and not to select the 'div'.

See the following example:

enter image description here

Is this possible?

Thank you!

Upvotes: 6

Views: 2842

Answers (2)

Quentin
Quentin

Reputation: 943509

There are two approaches you can take to this.

Handle it on the div

Test to see if the click was on the edit function

(event) => {
    const div = event.currentTarget;
    const edit = div.querySelector('.edit');
    if (edit === event.target) {
        return;
    }
    return this.handleTrackerCardClick();
}

This code example makes assumptions about the DOM structure. Adjust as needed. One of the assumptions is that the edit control is a single element with no element children. If it isn't, then you need to test to see if the click was any of the children too. Generally you would recursively check parentNode starting on event.target until you reached a match for div or edit.

Handle it on the edit control

Call the method that stops the event from propagating up the DOM and reaching the div.

(event) => {
    event.stopPropagation();
    this.do_edit_thing();
}

Upvotes: 6

bopbopbop
bopbopbop

Reputation: 522

I would simply place the inner, editable field as a sibling to the "parent". This way you can have a click handler for the outer div and the editable field with no overlap in terms of hierarchy.

Something like this:

function App() {
  return (
    <div style={{ border: "1px dashed red" }}>
      <div onClick={() => console.log("outer clicked")}>Outer click</div>
      <span
        style={{ border: "1px dashed blue" }}
        onClick={() => console.log("inner clicked")}
      >
        Inner click
      </span>
    </div>
  );
}

Check out a working example here

Upvotes: 1

Related Questions