css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

            
              <div id='app'>
  <h1>React.js from Scratch</h1>
  <h3><a href='http://ryanfunduk.com/articles/react-from-scratch'>ryanfunduk.com/articles/react-from-scratch</a></h3>
  <div id='mount'></div>
</div>

            
          
!
            
              #app { padding: 20px; font-family: sans-serif; }
h1, h3 { margin: 0; }
form { margin-top: 20px; }
input { font-size: 20px; padding: 2px 4px; }
ul { padding: 0; margin: 20px 0; list-style: none outside; }
li { padding: 4px 8px; line-height: 20px; }
span.toggle { font-weight: bold; color: #BBB; cursor: pointer; text-align: center; display: inline-block; width: 20px; height: 20px; margin-right: 6px; }
span.toggle:hover { color: black; }
a { color: #aaa; }
a:hover { color: #999; }
a.remove { margin-left: 10px; font-size: 12px; }
a.remove:hover { color: #BB0000; }

            
          
!
            
              /** @jsx dom */

//
// Main Application
//   Dispatcher, TodoStore and TodoActions
//   are from ryanfunduk.com/articles/flux-from-scratch
//

window.dispatcher = new Dispatcher()
window.todoStore = new TodoStore()
window.todoActions = new TodoActions()

dispatcher.register( function( payload ) {
  console.log( "ACTION: " + JSON.stringify(payload) )
} )

function TodoApp( props ) {
  var todoItems = []
  for( var i in props.todos ) {
    var todo = props.todos[i]
    todoItems.push( <TodoItem todo={todo} /> )
  }

  return (
    <div id='todo-app'>
      <form onSubmit={addTodo}>
        <label>New Todo:</label>&nbsp;
        <input value='' placeholder='type, then &crarr;' />
      </form>
      <ul>{todoItems}</ul>
    </div>
  )
    
  function addTodo( e ) {
    e.preventDefault()
    var input = e.target.querySelector('input')
    todoActions.createTodo( {
      title: input.value,
      completed: false
    } )
    input.value = ''
  }
}
  
function TodoItem( props ) {
  return (
    <li rel={props.todo.id}>
      <span class='toggle' onClick={toggle}>
        {props.todo.completed ? '&check;' : '&ndash;'}
      </span>
      {props.todo.title}
      <small>
        <a href='#' onClick={remove}
           className='remove'>(remove)</a>
      </small>
    </li>
  )
  
  function remove( e ) {
    e.preventDefault()
    var id = props.todo.id
    var todo = todoStore.getTodos()[id]
    todoActions.removeTodo( todo.id )
  }
  function toggle( e ) {
    var id = props.todo.id
    var todo = todoStore.getTodos()[id]
    todoActions.updateTodo(
      props.todo.id,
      { completed: !props.todo.completed }
    )
  }
}

// the element we want to render into
var target = document.getElementById('mount')

// the function that re-renders the whole app
function tick() {
  render(
    <TodoApp todos={todoStore.getTodos()} />,
    target
  )
}
// seed todos and trigger an update
todoActions.listTodos()

// when the store changes, re-render
todoStore.addListener( tick )

// first load
tick()


//
// Super naive virtual-DOM-like-thing below! :)
//

function dom( tag, attrs /*, children */ ) {
  if( typeof( tag ) == 'function' ) {
    // allows magic like <MyApp someProp='wow!' />
    attrs = attrs || {}
    attrs.children = children
    return tag( attrs )
  }
  else {
    var children = [].concat.apply(
      [], Array.prototype.slice.call(arguments).slice(2)
    )
    
    if( children.length > 1 ) {
      // if we have multiple children we need to convert
      // any text-only nodes into spans for tracking purposes
      for( var i in children ) {
        var child = children[i]
        if( child && typeof(child) != 'object' ) {
          children[i] = dom( 'span', null, child.toString() )
        }
      }
    }
    
    return { tag: tag, attrs: attrs, children: children }
  }
}

function prepare( tree, depth ) {
  depth = depth || [0]
  
  if( Array.isArray( tree ) ) {
    // recursively prepare arrays of elements (children)
    for( var i in tree ) {
      tree[i] = prepare( tree[i]||' ', depth.concat(i) )
    }
  }
  else if( typeof(tree) == 'string' ) {
    // string elements are at the bottom of the tree
    // and can just be inserted directly with no preparing
  }
  else {
    // 'tree' is a single element object
  
    // calculate depth/unique path to element
    // for tracking purposes
    tree._depth = [].concat( depth )
    
    // prepare children
    if( tree.children ) {
      tree.children = prepare( tree.children, depth )
    }
  }
  return tree
}

function renderNodes( nodes, target ) {
  if( Array.isArray(nodes) ) {
    for( var i in nodes ) {
      renderNodes( nodes[i], target )
    }
  }
  else {
    // actually just a single node
    var node = nodes

    if( node === null ) {
      // whitespace between elements
      target.appendChild( document.createTextNode(' ') )
    }
    else if( typeof(node) == 'string' ) {
      // at the bottom of the tree we have plain
      // text nodes, they are guaranteed to be single
      // children, so just set inner html of the container
      if( target.innerHTML !== node ) { target.innerHTML = node }
    }
    else {
      var el

      // find existing node first if possible
      var dataId = 'ui.'+node._depth.join('.')
      var existing = target.querySelector(
        node.tag + '[data-ui-id="' + dataId + '"]'
      )

      // the relative depth of this node in its container
      var relativeDepth = node._depth[node._depth.length-1]
      // the node at the same location in the existing DOM
      // if there is one
      var nodeAtSameLocation = target.children[relativeDepth]

      // if there's no existing node, or the node at the correct
      // place is not the *same* node, then we need a new one
      // to replace it with
      if( !existing || !nodeAtSameLocation.isSameNode(existing) ) {
        el = document.createElement( node.tag )
        el.dataset.uiId = dataId
      }
      else {
        el = existing
      }

      // various annoying attribute handling
      // IRL there would be a lot more stuff here
      if( node.attrs ) {
        var mapping = { className: 'class' }
        var special = [ 'onChange', 'onClick', 'value' ]
        for( var i in node.attrs ) {
          if( special.indexOf(i) != -1 ) { continue }
          el.setAttribute( mapping[i]||i, node.attrs[i] )
        }
        if( node.attrs.onChange ) { el.onkeyup = node.attrs.onChange }
        if( node.attrs.onClick ) { el.onclick = node.attrs.onClick }
        if( node.attrs.onSubmit ) { el.onsubmit = node.attrs.onSubmit }
        if( node.attrs.value ) { el.value = node.attrs.value }
      }

      // recursively render the children of this node
      if( node.children ) {
        renderNodes( node.children, el )

        // after rendering children at this depth
        // we need to clean up extra old nodes
        // because otherwise they will get left around
        // untouched (we aren't 'diffing' just brute-forcing)
        if( el.children.length > node.children.length ) {
          var stop = node.children.length
          for( var i = el.children.length; i > stop; i-- ) {
            el.removeChild( el.children[i-1] )
          }
        }
      }

      // if we have no existing node, we just need
      // to append the new one
      if( !existing ) { target.appendChild( el ) }
      // otherwise drop in the new node, which might be a no-op
      else { target.replaceChild( existing, el ) }
    }
  }
}
function render( tree, container ) {
  return renderNodes( prepare(tree), container )
}
            
          
!
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.
Loading ..................

Console