React.js Serverside rendering and Event Handlers

Viewed 15177

I am learning to use react.js and have some issues to use the event handlers. The final question would be: Is it possible to use server side rendering and send event handlers to the client automaticly?

Here is my example: I have an index.jsx which I render server side and send to the client

var React = require("react");
var DefaultLayout = require("./layout/default");

var LikeButton = React.createClass({
  getInitialState: function() {
    return {liked: false}; 
  }, 
  handleClick: function(event) {
    this.setState({liked: !this.state.liked});
  }, 
  render: function() {
    var text = this.state.liked ? 'like' : 'haven\'t liked';
    return (
      <p onClick={this.handleClick}>
        You {text} this. Click to toggle.
      </p>
    );
  } 
});

var IndexComponent = React.createClass({
   render: function(){
       return (
           <DefaultLayout title={this.props.name}>
                <div>
                        <h1>React Test</h1>
                </div>

                <div id="testButton">
                    <LikeButton/>
                </div> 

                <script type="text/babel" src="/js/react.js"></script>
           </DefaultLayout>
       )
   }   
});

But the "Like Button" does not have any interaction. To make it do something on click I have to add this code client side.

var LikeButton = React.createClass({
  getInitialState: function() {
    return {liked: false};
  },
  handleClick: function(event) {
    this.setState({liked: !this.state.liked});
  },
  render: function() {
    var text = this.state.liked ? 'like' : 'haven\'t liked';
    return (
      <p onClick={this.handleClick}>
        You {text} this. Click to toggle.
      </p>
    );
  }
});

ReactDOM.render(
  <LikeButton />,
  document.getElementById('testButton')
);

I only started out with react.js and maybe I am just missing some major concept here. But why does react.js not just create the code (which I now have to add manually to the client) when rendering the page server side? Like this, I have redundant code and it feels like this will be a mess in larger applications. At least react.js is smart enough to not draw two LikeButtons but to "bind" the one created server side to the client side component.

3 Answers

In additions to above answers, in CSR side you also have to replace ReactDOM.render to ReactDOM.hydrate

Also you can use same LikeButton file in SSR and CSR, only thing happen is SSR side onClick event will not response to any thing

Related