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?
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>
);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With