Created
March 6, 2015 09:01
-
-
Save kimmobrunfeldt/63c470bcb6b1679751a5 to your computer and use it in GitHub Desktop.
Preparing for null..
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
// utils.jsx | |
// Returns wanted data or null. You can specify default value instead of null. | |
// Remember that arrays are actually objects so you can get index of array with | |
// 'arr.0' | |
// e.g get(object, 'data.results.0') | |
function get(obj, attributePath, defaultValue) { | |
var opts = _.extend({defaultValue: null}, {defaultValue: defaultValue}); | |
if (!obj) { | |
return opts.defaultValue; | |
} | |
var returnObj = obj; | |
var attributes = attributePath.split('.'); | |
for (var i = 0; i < attributes.length; ++i) { | |
var attribute = attributes[i]; | |
returnObj = returnObj[attribute]; | |
if (!returnObj) { | |
return opts.defaultValue; | |
} | |
} | |
return returnObj; | |
} | |
// IndexComponent.jsx | |
var Index = React.createClass({ | |
render: function render() { | |
var data = this.props.data; | |
return ( | |
<div className="page"> | |
<h1>{utils.get(data, 'products.0.description')}</h1> | |
<h2>{utils.get(data, 'products.0.consumption')}</h2> | |
</div> | |
); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment