Skip to content

Instantly share code, notes, and snippets.

@elia
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elia/fad23026831a817e3526 to your computer and use it in GitHub Desktop.
Save elia/fad23026831a817e3526 to your computer and use it in GitHub Desktop.
Building a React.js component out of a piece of DOM
require 'react'
React = Native(`React`)
class DOM2React
def initialize(element)
@element = element
end
def virtual_dom
@virtual_dom ||= parse_element(`#@element[0]`)
end
def parse_element(native)
return native unless `'tagName' in #{native}`
attributes = `{}`
Array(`#{native}.attributes`).each do |attr|
attr = attr.to_n
name = `#{attr}.name`
name = 'className' if name == 'class'
`#{attributes}[#{name}] = #{attr}.value`
end
React.createElement(`#{native}.tagName`.downcase, attributes, *parse_children(native)).to_n
end
def parse_children(native)
Array(`#{native}.childNodes`).map { |c| parse_element(c.to_n) }
end
def render(parent)
# React.render(react_class.to_n, `#{parent}[0]`)
React.render(virtual_dom, parent)
end
def react_class
@react_class ||= React.createClass({displayName: 'SomeClass', render: -> {virtual_dom}}.to_n)
end
end
element = Element.find('article')
react = DOM2React.new(element)
react.render(element.parent) # re-render on itself
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment