Created
August 15, 2017 07:00
-
-
Save DC3/9ee38995f09791bf3ce0491853549859 to your computer and use it in GitHub Desktop.
React children
This file contains hidden or 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
React = @React or require 'react' | |
win = window | |
doc = win.document | |
range = (length) -> Array.apply(null, {length}).map(Number.call, Number) | |
randomInt = (min, max) -> Math.floor(Math.random() * (max - min + 1)) + min | |
memoized = (fn) -> | |
do (lookupTable = {}, key = undefined, value = undefined) -> | |
-> | |
key = JSON.stringify(arguments) | |
lookupTable[key] or= fn.apply(this, arguments) | |
getColorsArray = do -> | |
colors = [ | |
'#FF0000', '#f26522', '#fff200', | |
'#00a651', '#28abe2', '#2e3192', '#6868ff' | |
] | |
max = colors.length | |
memoized (length, offset = randomInt(0, max - 1)) -> | |
return [] unless length | |
return colors.slice(0) if length is max | |
randomStartColorArray = colors.slice(offset) | |
if length > max | |
list = range(Math.ceil(length / max)).reduce((arr) -> | |
arr.concat(colors) | |
, randomStartColorArray) | |
else | |
list = randomStartColorArray.concat(colors) | |
list.slice(0, length) | |
MyInput = React.Component.build class InputComponent | |
mixins: [React.DOM] | |
render: -> @input @props | |
class LabelComponent extends React.Component | |
mixins: [React.DOM] | |
renderItems: -> | |
text = @props.valueLink.value or "rainbow-label" | |
colors = getColorsArray(text.length) | |
text.split('').map (char, index) => | |
style = color: colors[index] | |
@span {key: index, style}, char | |
render: -> | |
@label null, @renderItems() | |
MyLabel = LabelComponent.toComponent() | |
MyButton = React.Component.toComponent class ButtonComponent | |
mixins: [React.DOM] | |
render: -> | |
{requestChange, value} = @props.valueLink | |
@button({ | |
onClick: requestChange.bind(null, 'Button Click!!!') | |
}, value or 'button') | |
class ExampleComponent extends React.Component | |
mixins: [React.DOM] | |
getInitialState: -> | |
name: 'DC3' | |
handleChange: (name) -> | |
@setState {name} | |
renderChildren: -> | |
valueLink = | |
value: @state.name | |
requestChange: @handleChange | |
@props.children.map (child, index) => | |
@li {key: index}, | |
child {valueLink} | |
render: -> | |
@div null, | |
"hello world form react! #{@state.name}" | |
@hr null | |
@ul null, @renderChildren() | |
Example = ExampleComponent.build() | |
win.onload = -> | |
componentList = [MyLabel, MyInput, MyButton] | |
components = range(randomInt(10, 20)).map -> | |
componentList[randomInt(0, componentList.length - 1)] | |
win.app = React.render Example(null, components), doc.getElementById('main') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment