Apply style “cursor: pointer” to all React components with onClick function

I am not certain there’s a good way to do this automatically without using some sort of mechanism that intercepts the creation of React elements and modifies them (or perhaps source level transforms). For example, using Babel, you could use babel-plugin-react-transform and add a className to all elements with an onClick prop using something along these lines (warning: pseudocode):

export default function addClassNamesToOnClickElements() {
  return function wrap(ReactClass) {
    const originalRender = ReactClass.prototype.render;

    ReactClass.prototype.render = function render() {
      var element = originalRender.apply(this, arguments);
      return addClickClassNamesToApplicableElements(element);
    }

    return ReactClass;
  }
}

function addClassNamesToApplicableElements(elem) {
  if (!elem || typeof elem === "string") return elem;

  const children = elem.children;
  const modifiedChildren = elem.props.children.map(addClassNamesToApplicableElements);

  if (elem.props.onClick) {
    const className = elem.props.className || "";

    return {
      ...elem,
      props: {
        ...elem.props,
        className: (className + " hasOnClick").trim(),
        children: modifiedChildren
      }
    };
  } else {
    return {
      ...elem,
      props: {
        ...elem.props,
        children: modifiedChildren
      }
    }
  };
}

Here’s a quick example of the second part working: https://bit.ly/1kSFcsg

Leave a Comment