123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              body {
	font-family: Sans-Serif;
	background: #fafafa;
}

a {
	text-decoration: none;
	padding-left: 5px;
}

ul {
	list-style-type: none;
	padding: 0;
}

button {
	background: none;
	box-shadow: none;
	border: 1px solid #dd1224;
	color: #dd1224;
	cursor: pointer;
	width: 60px;
	outline: 0 !important;
	margin: 5px 0;
}

b {
	display: inline-block;
	-webkit-transition: 0.1s ease-in-out;
	transition: 0.1s ease-in-out;
}

button:active b {
	-webkit-transform: scale(1.3);
	transform: scale(1.3);
}
            
          
!
            
              /** @jsx DiyReact.createElement */

const DiyReact = importFromBelow();

const randomLikes = () => Math.ceil(Math.random() * 100);

const stories = [
  {name: "React", url: "https://reactjs.org/", likes: randomLikes()},
  {name: "Node", url: "https://nodejs.org/en/", likes: randomLikes()},
  {name: "Webpack", url: "https://webpack.js.org/", likes: randomLikes()}
];

const ItemRender = props => {
  const {name, url} = props;
  return (
    <a href={url}>{name}</a>
  );
};

class App extends DiyReact.Component {
  render() {
    return (
      <div>
        <h1>DiyReact Stories</h1>
        <ul>
          {this.props.stories.map(story => {
            return <Story name={story.name} url={story.url} />;
          })}
        </ul>
      </div>
    );
  }
  
  componentWillMount() {
    console.log('execute componentWillMount');

  }
  
  componentDidMount() {
    console.log('execute componentDidMount');
  }
  
  componentWillUnmount() {
    console.log('execute componentWillUnmount');
  }
}

class Story extends DiyReact.Component {
  constructor(props) {
    super(props);
    this.state = { likes: Math.ceil(Math.random() * 100) };
  }
  like() {
    this.setState({
      likes: this.state.likes + 1
    });
  }
  render() {
    const { name, url } = this.props;
    const { likes } = this.state;
    const likesElement = <span />;
    const itemRenderProps = {name, url};
    return (
      <li>
        <button onClick={e => this.like()}>{likes}<b>❤️</b></button>
        <ItemRender {...itemRenderProps} />
      </li>
    );
  }
  
  // shouldcomponentUpdate() {
  //   return true;
  // }
  
  componentWillUpdate() {
    console.log('execute componentWillUpdate');
  }
  
  componentDidUpdate() {
    console.log('execute componentDidUpdate');
  }

}

DiyReact.render(<App stories={stories} />, document.getElementById("root"));

/* 🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼🌼 */

function importFromBelow() {
  const TEXT_ELEMENT = 'TEXT_ELEMENT';
  
  function updateDomProperties(dom, prevProps, nextProps) {
    const isEvent = name => name.startsWith("on");
    const isAttribute = name => !isEvent(name) && name != "children";

    // Remove event listeners
    Object.keys(prevProps).filter(isEvent).forEach(name => {
      const eventType = name.toLowerCase().substring(2);
      dom.removeEventListener(eventType, prevProps[name]);
    });

    // Remove attributes
    Object.keys(prevProps).filter(isAttribute).forEach(name => {
      dom[name] = null;
    });

    // Set attributes
    Object.keys(nextProps).filter(isAttribute).forEach(name => {
      dom[name] = nextProps[name];
    });

    // Add event listeners
    Object.keys(nextProps).filter(isEvent).forEach(name => {
      const eventType = name.toLowerCase().substring(2);
      dom.addEventListener(eventType, nextProps[name]);
    });
  }
  
  let rootInstance = null;
  function render(element, parentDom) {
    const prevInstance = rootInstance;
    const nextInstance = reconcile(parentDom, prevInstance, element);
    rootInstance = nextInstance;
  }
  
  function reconcile(parentDom, instance, element) {
    if (instance === null) {
      const newInstance = instantiate(element);
      // componentWillMount
      newInstance.publicInstance
        && newInstance.publicInstance.componentWillMount
        && newInstance.publicInstance.componentWillMount();
      parentDom.appendChild(newInstance.dom);
      // componentDidMount
      newInstance.publicInstance
        && newInstance.publicInstance.componentDidMount
        && newInstance.publicInstance.componentDidMount();
      return newInstance;
    } else if (element === null) {
      // componentWillUnmount
      instance.publicInstance
        && instance.publicInstance.componentWillUnmount
        && instance.publicInstance.componentWillUnmount();
      parentDom.removeChild(instance.dom);
      return null;
    } else if (instance.element.type !== element.type) {
      const newInstance = instantiate(element);
      // componentDidMount
      newInstance.publicInstance
        && newInstance.publicInstance.componentDidMount
        && newInstance.publicInstance.componentDidMount();
      parentDom.replaceChild(newInstance.dom, instance.dom);
      return newInstance;
    } else if (typeof element.type === 'string') {
      updateDomProperties(instance.dom, instance.element.props, element.props);
      instance.childInstances = reconcileChildren(instance, element);
      instance.element = element;
      return instance;
    } else {
      if (instance.publicInstance
          && instance.publicInstance.shouldcomponentUpdate) {
        if (!instance.publicInstance.shouldcomponentUpdate()) {
          return;
        }
      }
      // componentWillUpdate
      instance.publicInstance
        && instance.publicInstance.componentWillUpdate
        && instance.publicInstance.componentWillUpdate();
      instance.publicInstance.props = element.props;
      const newChildElement = instance.publicInstance.render();
      const oldChildInstance = instance.childInstance;
      const newChildInstance = reconcile(parentDom, oldChildInstance, newChildElement);
      // componentDidUpdate
      instance.publicInstance
        && instance.publicInstance.componentDidUpdate
        && instance.publicInstance.componentDidUpdate();
      instance.dom = newChildInstance.dom;
      instance.childInstance = newChildInstance;
      instance.element = element;
      return instance;
    }
  }

  function reconcileChildren(instance, element) {
    const {dom, childInstances} = instance;
    const newChildElements = element.props.children || [];
    const count = Math.max(childInstances.length, newChildElements.length);
    const newChildInstances = [];
    for (let i = 0; i < count; i++) {
      newChildInstances[i] = reconcile(dom, childInstances[i], newChildElements[i]);
    }
    return newChildInstances.filter(instance => instance !== null);
  }
  
  function instantiate(element) {
    const {type, props = {}} = element;
    
    const isDomElement = typeof type === 'string';
    const isClassElement = !!(type.prototype && type.prototype.isReactComponent);
    if (isDomElement) {
      // 创建dom
      const isTextElement = type === TEXT_ELEMENT;
      const dom = isTextElement ? document.createTextNode('') : document.createElement(type);

      // 设置dom的事件、数据属性
      updateDomProperties(dom, [], element.props);
      const children = props.children || [];
      const childInstances = children.map(instantiate);
      const childDoms = childInstances.map(childInstance => childInstance.dom);
      childDoms.forEach(childDom => dom.appendChild(childDom));
      const instance = {element, dom, childInstances};
      return instance;
    } else if (isClassElement) {
      const instance = {};
      const publicInstance = createPublicInstance(element, instance);
      const childElement = publicInstance.render();
      const childInstance = instantiate(childElement);
      Object.assign(instance, {dom: childInstance.dom, element, childInstance, publicInstance});
      return instance;
    } else {
      const childElement = type(element.props);
      const childInstance = instantiate(childElement);
      const instance = {
        dom: childInstance.dom,
        element,
        childInstance
      };
      return instance;
    }
  }
  
  function createTextElement(value) {
    return createElement(TEXT_ELEMENT, {nodeValue: value});
  }
  
  function createElement(type, props, ...children) {
    props = Object.assign({}, props);
    props.children = [].concat(...children)
      .filter(child => child != null && child !== false)
      .map(child => child instanceof Object ? child : createTextElement(child));
    return {type, props};
  }
  
  function createPublicInstance(element, instance) {
    const {type, props} = element;
    const publicInstance = new type(props);
    publicInstance.__internalInstance = instance;
    return publicInstance;
  }
  
  class Component {
    constructor(props) {
      this.props = props;
      this.state = this.state || {};
    }
    
    setState(partialState) {
      this.state = Object.assign({}, this.state, partialState);
      // update instance
      const parentDom = this.__internalInstance.dom.parentNode;
      const element = this.__internalInstance.element;
      reconcile(parentDom, this.__internalInstance, element);
    }
  }
  
  Component.prototype.isReactComponent = {};
  
  return {
    render,
    createElement,
    Component
  };
}

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console