Skip to content

Instantly share code, notes, and snippets.

@c80609a
Forked from dgellow/react-tutorial.coffee
Created March 25, 2020 13:28
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 c80609a/8dacbe35a53659814fa010b5b53ea010 to your computer and use it in GitHub Desktop.
Save c80609a/8dacbe35a53659814fa010b5b53ea010 to your computer and use it in GitHub Desktop.
React.js tutorial in coffeescript. http://facebook.github.io/react/docs/tutorial.html
dom = React.DOM
CommentBox = React.createClass
getInitialState: ->
{data: []}
loadCommentsFromServer: ->
$.ajax
url: 'comments.json',
dataType: 'json',
success: (data) =>
@setState {data: data}
error: (xhr, status, err) ->
console.error 'comments.json', status, err.toString()
handleCommentSubmit: (comment) ->
comments = @state.data
newComments = comments.concat [comment]
@setState {data: newComments}
$.ajax
url: @props.url
type: 'POST'
data: comment
success: (data) =>
@setState {data: data}
componentWillMount: ->
@loadCommentsFromServer()
setInterval @loadCommentsFromServer, @props.pollInterval
render: ->
dom.div {className: 'commentBox'},
dom.h1(null, 'Comments'),
CommentList({data: @state.data}),
CommentForm({onCommentSubmit: @handleCommentSubmit})
CommentList = React.createClass
render: ->
commentNodes = @props.data.map (comment) ->
Comment {author: comment.author}, comment.text
dom.div {className: 'commentList'}
commentNodes
CommentForm = React.createCLass
handleSubmit: (ev) ->
author = @refs.author.getDOMNode().value.trim()
text = @refs.text.getDOMNode().value.trim()
@props.onCommentSubmit {author: author, text: text}
@refs.author.getDOMNode().value = ''
@refs.text.getDOMNode().value = ''
preventDefault ev
render: ->
dom.form {className: 'commentForm', onSubmit: @handleSubmit}
dom.input(
type: 'text'
placeholder: 'Your name'
ref: author
),
dom.input(
type: 'text'
placeholder: 'Say something fun !'
ref: text
),
dom.input(
type: 'submit'
value: 'Post'
)
Comment = React.createClass
render: ->
converter = new Showdown.converter()
rawMarkup = converter.makeHtml @props.children.toString()
dom.div {className: 'comment'},
dom.h2({className: 'commentAuthor'},
@props.author
),
dom.span({dangerouslySetInnerHTML: {__html: rawMarkup}})
React.renderComponent
CommentBox({url: 'comments.json', pollInterval: 2000}),
document.getElementById('content')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment