Skip to content

Instantly share code, notes, and snippets.

@stevoland
Last active August 29, 2015 14:08
Show Gist options
  • Save stevoland/e127f5e9854d0862701e to your computer and use it in GitHub Desktop.
Save stevoland/e127f5e9854d0862701e to your computer and use it in GitHub Desktop.
shouldRenderForClientMixin
var shouldRenderForClientMixin = {
componentDidMount: function () {
this.setState({
renderForClient: true
})
},
shouldRenderForClient: function () {
return typeof document !== 'undefined' && this.state && this.state.renderForClient;
}
};
var Map = React.createClass({
mixins: [shouldRenderForClientMixin],
render: function() {
if (!this.shouldRenderForClient()) {
return <img />;
}
return <FancyClientSideMap />;
}
});
@stratospark
Copy link

I needed to do something like this because node was throwing an exception when it couldn't find document. Also, when React runs on the client, it seems to call shouldRenderClient before componentDidMount, so there is no state yet to check, which throws an exception that I need to catch.

shouldRenderForClient: function () {
    try {
        return typeof(document) !== "undefined" && this.state.renderForClient;
    } catch (e) {
        return false;
    }
}

@stevoland
Copy link
Author

@stratospark thanks for testing. you're right of course. I'll change it to:

shouldRenderForClient: function () {
  return typeof document !== 'undefined' && this.state && this.state.renderForClient;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment