Created
March 9, 2016 18:21
-
-
Save noahlt/9fab57026b36711f7e4b to your computer and use it in GitHub Desktop.
Catch errors in render() with SafeReactComponent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var React = require('react'); | |
var _ = require('underscore'); | |
// Catches errors in render() and returns null so that we don't | |
// break the entire React app. | |
var SafeReactComponent = function(classObj) { | |
var originalRender = classObj.render; | |
var displayName = classObj.displayName || 'unknown component'; | |
return React.createClass(_.extend(classObj, { | |
render: function() { | |
try { | |
return originalRender.bind(this)(); | |
} catch (e) { | |
console.error('['+displayName+'] render error:', e); | |
return null; | |
} | |
}, | |
})); | |
}; | |
module.exports = SafeReactComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment