Skip to content Skip to sidebar Skip to footer

Higher Order React Component For Click Tracking

I'd like to implement a higher order react component which can be used to easily track events (like a click) on any React component. The purpose of this is to easily hook clicks (a

Solution 1:

It's impossible to get a reference to underlying DOM node (and there can be more than one of them) from Wrapper React element by regular means, like a ref or ReactDOM.findDOMNode. In order to do that, element children should be traversed recursively.

An example:

remapChildren(children) {
  const { onClick } = this;

  return React.Children.map(
    children,
    child => {   
      if (typeof child.type === 'string') {
        return React.cloneElement(child, { onClick });
      } elseif (React.Children.count(child.props.children)) {
        return React.cloneElement(child, { children: this.remapChildren(
          child.props.children
        ) });
      }
    }
  );
}

render() {
  returnthis.remapChildren(this.props.children);
}

remapChildren places onClick only on DOM elements. Notice that this implementation skips nested DOM elements.

Post a Comment for "Higher Order React Component For Click Tracking"