Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window is not Defined on Prerender

I'm experimenting with React.js with Rails via react-rails(1.0.0pre) and have had some troubles pre-rendering responsive elements that rely on the window size. Whenever I create a component that uses window, I get the following error: [React::Renderer] ReferenceError: window is not defined when attempting to render the component to a string in my Rails view. For example, my component:

/** @jsx React.DOM */

var Example = React.createClass({  
  getInitialState: function() {    
    return { 
      windowWidth: $(window).width()
    };
  },

  render: function () {

    return (
      <div className="example-wrapper">
        {this.props.label}
        {this.state.windowWidth}
      </div>
    );
  }
});

and my view with props:

<%= react_component('Example', {name: 'Window width is:'}, { prerender: true }) %>

Is it possible to reference the window in React's virtual DOM?

like image 899
Kombo Avatar asked Dec 14 '22 21:12

Kombo


1 Answers

On the server when prerendering, you can't query the window's width – how could you? The server doesn't have access to that information and so it couldn't possibly be included in the HTML that's sent down. Instead, you want to have some initial state that the component is rendered with, and then update upon mounting when you know the window object is accessible:

var Example = React.createClass({  
  getInitialState: function() {    
    return { 
      windowWidth: 0  // or "loading..." or whatever
    };
  },

  componentDidMount: function() {
    // Triggers a re-render
    this.setState({
      windowWidth: $(window).width()
    });
  },

  render: function () {
    return (
      <div className="example-wrapper">
        {this.props.label}
        {this.state.windowWidth}
      </div>
    );
  }
});
like image 62
Sophie Alpert Avatar answered Dec 29 '22 23:12

Sophie Alpert