Last active
August 29, 2015 14:17
-
-
Save elia/fad23026831a817e3526 to your computer and use it in GitHub Desktop.
Building a React.js component out of a piece of DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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