Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created January 27, 2017 15:39
Show Gist options
  • Save jgaskins/0cca15ce36737f87b28e8e7d4bbeb517 to your computer and use it in GitHub Desktop.
Save jgaskins/0cca15ce36737f87b28e8e7d4bbeb517 to your computer and use it in GitHub Desktop.
Stateful Clearwater components using nested Clearwater apps
# Wrapper for a UI component that needs to maintain its own state
class Toggle
include Clearwater::BlackBoxNode
attr_reader :app, :component :state
def initialize(state=false)
@state = state
end
def mount element
@component = Component.new(@state)
@app = Clearwater::Application.new(component: component, element: element)
@app.render # No need to use `call` because we don't want to mount the app
end
def update previous
@app = previous.app
# uncomment the following line if you want to change the component's state with
# this wrapper's constructor params when updating:
# @component.state = @state
@app.render
end
# The actual UI component we're going to use
class Component
include Clearwater::Component
def initialize(state)
@state = state
end
def render
div(
onclick: method(:toggle!),
style: {
background_color: toggled? ? :green : red,
width: '1em',
height: '1em',
}
)
end
def toggle!
@state = !@state
end
def toggled?
!!@state
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment