title: Selectively rendering optional component properties in React JSX
body: <p>I have a use case where I have an Image component that has a required "src" attribute and an optional "link" attribute which looks like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>var Image = React.createClass({
  
  propTypes: {
    link: React.PropTypes.string,
    event: React.PropTypes.object,
    src: React.PropTypes.string.isRequired
  },
  
  handleClick: function(event, link) {
     analytics.track(event)
      .then(function() {
        window.location = link;
      });
  },
  
  render: function() {
    return (
      &lt;img className='image' src={this.props.src} onClick={this.handleClick.bind(this, this.props.event, this.props.link)} /&gt;
    );
  } });
  </code></pre>
  
  <p>If I want to selectively include optional props when I call the Image component, how would I do that elegantly?  My initial idea was to do a ternary expression like this, except this is not valid JSX:</p>
  
  <pre class="lang-js prettyprint-override"><code>render: function() {
      return (
          &lt;Image src={this.props.src} {this.props.link.hasOwnProperty('value') ? link=this.props.link.value : ''} /&gt;
      )
  }
  </code></pre>
  
  <p>In the example above "this.props.link" is an object that may or may not contain a property called "value" which includes the hyperlink to browse to when the Image is clicked.  Also, rather than simply supplying an empty string as the value for the "link" prop, I would prefer to simply leave it out altogether if there is no link.value present.</p>
  
  <p>My reasoning for this is so that on the Image component I can add the css "img:hover {cursor: pointer;}" only if the img actually links somewhere, as opposed to setting it globally which violates UX rules for my app.</p>
  
  <p>I know that I can simply render the "link" prop inside a ternary where it includes the value of the link if it exists and is an empty string if it doesn't, but for curiousity's sake I wanted to see if there maybe was another way to accomplish this.</p>
  
  <p>I also would like to avoid having to do a bunch of conditional statements that create a lot of redundant JSX code like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>render: function() {
      if (this.props.link.hasOwnProperty('value')) {
          return &lt;Image link={this.props.link.value} src={this.props.src.value} /&gt;;
      } else {
          return &lt;Image src={this.props.src.value} /&gt;;
      }
      .... // other optional properties
  }
  </code></pre>
  
  <p>Imagine how out of hand that would get if you have a lot of optional props that you want to leave off...</p>