0

When click element want to track user click behavior in rootHandler. eg:

  • When click App3. becase of App3 has bind onClick event, so track it.
  • When click App1, App2. becase of App1, App2 does not bind onClick event, so does not track it.
export default function App() {
  const rootHandler = (e) => {
    if (e.hasBindOnClick) {
      console.log("track", e.target.textContent);
    }
  };

  const click3 = (e) => {
    e.hasBindOnClick = true;
    console.log("click3", e);
  };

  return (
    <div className="root" onClick={rootHandler}>
      <div className="App1">App1</div>
      <div className="App2">App2</div>
      <div className="App3" onClick={click3}>
        App3
      </div>
    </div>
  );
}

Now, I need set hasBindOnClick flag in each click handler, but there are so many handler in our project. Is there some universial way to do this?

https://codesandbox.io/s/jolly-meadow-hgm5t4?file=/src/App.js:24-496

1 Answer 1

1

Don't (try to) set attributes on the event as it bubbles up, but set an attribute on the elements you want to track.

This is useful also because the value of the track data value (or any other attribute) could store related data.

function App() {
  const rootHandler = (e) => {
    if (e.target.dataset.track) console.log("track", e.target.textContent);
  };

  return (
    <div className="root" onClick={rootHandler}>
      <div className="App1">App1</div>
      <div className="App2">App2</div>
      <div className="App3" data-track="1">
        App3
      </div>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

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.