This is a prototype which use react-rails gem with rails 4.1.9.
rails new proto_react_railsI used scaffold genarator for a quick start:
rails g scaffold Post title:string content:text attachment:string media:stringFix your config/routes.rb to go to the home page, by changing to:
root "posts#index"Gemfile:
gem "react-rails", github: "reactjs/react-rails", branch: "master"
gem "showdown-rails"And let's add the assets to application.js file:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require showdown
//= require react
//= require_tree .Gemfile:
gem 'carrierwave'And restart your rails server. To generate an uploader for attachment:
rails g uploader AttachmentOpen your model file and mount this uploader:
mount_uploader :attachment, AttachmentUploaderGemfile:
gem "bootstrap-sass"
gem "autoprefixer-rails"Rename app/assets/stylesheets/application.css to application.css.scss and change it to the following:
@import "bootstrap-sprockets";
@import "bootstrap";Note that, when you want to use any classes in react component files(jsx), you have to rename html class with "className" instead of "class". Like that:
<div className="panel-body">
</div>At this prototype, I use post model, so rename
app/assets/javascripts/posts.js.coffeeto
app/assets/javascripts/posts.js.jsxNow, you can write react in this file, anymore.
To list posts at root page with react, copy
/app/views/posts/index.html.erbto your root file. Copy
/app/assets/javascripts/posts.js.jsxto your component file and make necessary changes.
There is a script tag in my app/views/posts/index.html.erb file. I call "postsCreator" function to list posts in the "div#content". Be sure that,
<div id="content"></div>rendered when you call "postsCreator" function. If you call this function at app/assets/javascripts/posts.js.jsx, call like that:
$( document ).ready(function() {
$(function() {
React.render(
<Posts url="posts.json" />,
document.getElementById("content")
)
});
});I used FormData with ajax file upload. Generate a formData append all these which you send. Be sure that, you set processData, contentType, dataType
processData: false,
contentType: false,
dataType: 'json'To render post's title:
{this.props.title}And post's attachment (image for example):
{this.props.attachment.url}After a post is created, ajax will return success message and the new post (data). At this point I call:
this.props.onNewPost(data);This call "addPost" function to add this new post to posts-list. To manipulate posts-list:
var updatedPosts = this.state.posts.slice();
updatedPosts.push(post);
this.setState({posts: updatedPosts});React will rerender posts-list after you change state.