I've read in the React docs that if type statements can't be used in JSX code, because of the way JSX renders into javascript, it doesn't work out as one would expect.
But is there any reason why implementing an if component is a bad idea? It seems to work fine from my initial tests, and makes me wonder why this isn't done more often?
Part of my intent is to allow react development to be as much as possible, markup based - with as little javascript as possible. This approach, to me, feels like more of a data driven approach.
You can check it out here on JS Fiddle
<script type='text/javascript' src=https://unpkg.com/[email protected]/dist/JSXTransformer.js></script>
<script type='text/javascript' src=https://unpkg.com/[email protected]/dist/react-with-addons.js></script>
<script type=text/jsx>
/** @jsx React.DOM */
var If = React.createClass({
displayName: 'If',
render: function()
{
if (this.props.condition)
return <span>{this.props.children}</span>
return null;
}
});
var Main = React.createClass({
render: function() {
return (
<div>
<If condition={false}>
<div>Never showing false item</div>
</If>
<If condition={true}>
<div>Showing true item</div>
</If>
</div>
);
}
});
React.renderComponent(<Main/>, document.body);
</script>
Running the above results in:
Showing true item