Skip to content

Instantly share code, notes, and snippets.

@kellysutton
Created December 23, 2020 14:38
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 kellysutton/6eaf6e4c27a7c9173a8731dc84f539f4 to your computer and use it in GitHub Desktop.
Save kellysutton/6eaf6e4c27a7c9173a8731dc84f539f4 to your computer and use it in GitHub Desktop.
Sketch of React rendering Rails ERB
<main>
<% @posts.each do |post| %>
<!-- Under the hood, we find the right file in webpack and attach the expected object to window.Post -->
<Post
title={post.title}
description={post.description}
/>
<% end %>
</main>
<!-- We could take this another step further and execute JS in the template rendering and ask React to
spit out the resulting HTML for drawing in the browser. -->
<!-- Executing JS and rendering the HTML also gives us an opportunity to catch
[prop-]type mismatches during development. -->
<!--
This might be the equivalent of the following in a more traditional world, minus the server-side rendering.
-->
<main>
<% @posts.each do |post| %>
<div id="post-<%= post.id"></div>
<% end %>
</main>
<script>
<% @posts.each do |post| %>
ReactDOM.render(
React.createElement(window.Post, { title: <%= post.title.to_json %>, description: <%= post.description.to_json %> }),
document.findElementById("post-<%= post.id %>")
);
<% end %>
</script>
<!--
As we incrementally adopt React, it starts to "creep up" the DOM. It's really easy to change the boundary where
ERB stops and React starts.
-->
<main>
<Blog posts={@posts} />
</main>
<!--
This might be the equivalent of the following in a more traditional world.
-->
<main>
<div id="blog"></div>
</main>
<script>
ReactDOM.render(
React.createElement(window.Blog, { posts: <%= @posts.to_json %> }),
document.findElementById("blog")
);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment