React Kompose Clock Demo

A simple clock built with React Kompose

by arunoda

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.min.js "></script>
<script src="https://cdn.rawgit.com/kadirahq/react-komposer/master/dist/browser.min.js"></script>
<div id="react-root">
</div>

Babel + JSX

// Create a component to display Time
// const Time = ({time}) => (<div>{time}</div>);

// Not yet, supported for React Stateless components.

const original = React.createElement;
let currentComponent = null;
React.createElement = function(type, props, children) {
	//console.log("hacked:", typeof type === 'string'? type : type.name, props);
	if (typeof type !== 'string') {
  	if (!type.__debugHijacked) {
      const compName = type.displayName || type.name;
      const originalRender = type.prototype.render;
      type.prototype.render = function() {
      	currentComponent = compName
        const value = originalRender.call(this);
        currentComponent = null;
        return value;
      };
    	type.__debugHijacked = true;
    }
  } else {
  	for (var name in props) {
      const prop = props[name];
      props[name] = hijackProp(name, prop);
    }
  }
  
  function hijackProp(name, prop) {
  	if (prop.__hijacked) {
      return prop;
    }
    
    if (typeof prop !== 'function') {
      return prop;
    }
    
    const comps = currentComponent;
    const newProp = function() {
      console.log(`Event ${name} in components: ${comps}`);
    	prop();
    }
    
    newProp.__hijacked = true;
    return newProp;
  }
  
  return original.apply(this, arguments);
};

function printMe() {
	console.log("Hello  Bro");
}

class Time2 extends React.Component {
  render() {
  	return (
  		<button onClick={printMe}>Click Me</button>
  	);
  }
}

class Time extends React.Component {
  render() {
  	return (
  		<div>
      	{this.props.time}
        <Time2 />
      </div>
  	);
  }
}

// Create the composer function and tell how to fetch data
const composerFunction = (props, onData) => {
	const handler = setInterval(() => {
  	const time = new Date().toString();
    onData(null, {time});
  }, 1000);
  
  const cleanup = () => clearInterval(handler);
  return cleanup;
};

// Compose the container
const Clock = ReactKomposer.compose(composerFunction)(Time);

// Render...