Shared JavaScript that runs on both the client & server
A JavaScript library for building user interfaces
The V in MVC
This is a React component:
var HiButton = React.createClass({ handleClick: function () { alert("hi " + this.props.name); }, render: function () { return ( <button onClick={this.handleClick}> Say hi </button> ); } });
React.renderComponent(<HiButton name="Ben" />, document.body);
React.renderComponentToString(<HiButton name="Ben" />);
returns this string...
<button data-reactid=".1" data-react-checksum="762252829"> Say hi </button>
React component + ability to run JS
=
Ability to render a React component to a HTML string
We can run JS on servers now...
... so we can render React components on the server!
React is a pretty great option for server-rendered views.
ERB template:
What is a template?
Templates are just functions.
Early on they were big, ugly, complicated functions:
Source: W3Schools
We reacted to unmaintainable spaghetti templates
But we wanted a little bit of flexibility...
(but the occasional loop or conditional is ok...)
Sometimes we need to do string manipulation, or sorting...
(except loops & conditionals, which are still arbitrarily allowed in templates)
Current state of play for server-rendered views:
A better server-rendered View: React components
client-side JS is a bit of a thing
Server
<body> <%= React.renderComponentToString(<UserProfileView />); %> </body>
Browser
React.renderComponent(<UserProfileView />, document.body);
When browser-React encounters HTML rendered by server-React, it just adds event listeners.
Same component file used on client & server!
But what if my back end isn't node.js?
How can I do this in Rails/PHP/.NET/whatever?
Your app might already talks to other services over HTTP
https://github.com/facebook/react/tree/master/examples/server-rendering
You can render a view on the server based on application state at any point in time.
If something goes wrong in the browser, no worries! Submit a form, click a link...
The server will render the app in exactly the same state as the client JS would have.
live demo time...
We're hiring awesome developers!
Server-rendered React components in Rails