I'm used to using Handlebars, what are some suggested React-y ways to emulate something like this (not necessarily a direct translation, but a similar effect):
var Beer = React.createClass({
render: function(){
return (
<div className="media">
<div className="media-body">
{{#if beer.name}}<h4 className="media-heading">{beer.name}</h4>{{/if}}
{{#if beer.icon}} <img className="media-object" src={beer.icon} />{{/if}}
{{#if beer.style.name}}<p>{beer.style.name} </p>{{/if}
etc...
</div>
</div>
)
}
});
module.exports = Beer;
My approach is slightly different from WiredPrarie's:
var Beer = React.createClass({
render: function(){
return (
<div className="media">
<div className="media-body">
{ beer.name && <h4 className="media-heading">{beer.name}</h4> }
{ beer.icon && <img className="media-object" src={beer.icon} /> }
{ beer.style.name && <p>{beer.style.name} </p> }
etc...
</div>
</div>
)
}
});
module.exports = Beer;
For simple conditions, you could use a technique like this:
var Beer = React.createClass({
render: function(){
var beer = this.props.beer;
return (
<div>
<div>
{ beer.name ? <h4>{beer.name}</h4> : null }
{ beer.icon ? <img src={beer.icon} /> : null }
{ beer.style && beer.style.name ? <p>{ beer.style.name }</p> : null }
{ beer.style && beer.style.color ? <div>{ beer.style.color }</div> : null }
</div>
</div>
)
}
});
var beer = {
name: 'Pale Ale',
style: {
name: 'Very Very Pale'
}
};
React.render(<Beer beer = { beer } />,
document.getElementById('content'));
I've just used the JavaScript conditional ternary operator to return an element if there's value at a specific property (although you'll want a slightly more robust string/value check than that ... I just wanted to keep it short to illustrate the point).
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