On Github ncherro / backbone-react-presentation
render the Posts component into #content
pass in a backbone collection we'll be able to refrence with @props.posts
define ['react', 'ui/posts/index', 'collections/posts],
(React, Posts, PostsCollection) ->
React.renderComponent(
Posts(
posts: new PostsCollection
),
document.getElementById('content')
)
React.renderComponent() will probably be called in a backbone router action
bind our custom @handleUpdate callback to the collection's add / remove / reset events, then call @props.posts.fetch()
when the collection changes, @handleUpdate changes our component's state to trigger render
define ['react', 'ui/posts/show', 'ui/common/loading'],
(React, Post, Loading) ->
D = React.DOM
React.createClass
# event handlers
handleUpdate: () ->
# change the state to trigger re-rendering
@setState { loading: false }
# react
getInitialState: ->
loading: true
componentWillMount: ->
# update our state when the backbone collection changes
@props.posts.on 'add remove reset', @handleUpdate, @
# fetch posts!
@props.posts.fetch()
componentWillUnmount: ->
# unbind event handlers
@props.post.off null, null, @
render: ->
if @state.loading
# render the Loading component
Loading()
else
# loop through the collection, rendering a Post component for each model.
D.div { className: 'posts' }, @props.posts.map (post) ->
Post { post: post }
ui/posts/index.coffee
The 'show' component just renders, displaying info from the @props.post backbone model using the backbone get method
define ['react'], (React) ->
D = React.DOM
React.createClass
render: ->
D.div { className: 'post' }, [
D.h3 {}, @props.post.get('title')
D.div { dangerouslySetInnerHTML: { __html: @props.post.get('copy') }}
]
ui/posts/show.coffee
Component specs and lifecycle are described here.
Every react component must define a render() method, but I ended up using these callbacks on every stateful component:
React gives us an efficient way to build and render stateful UI components
Using React + Backbone, we can:
set up a React component with a callback that triggers a simple state change, which triggers a re-render instantiate the component, passing in a Backbone model / collection use on() bind our component's callback to certain model / collection events use off() unbind events when the component unmounts