Paul Paul - 1 year ago 49
Javascript Question

React - Optionally wrap an item in a link

I have a React component that displays a title and some text. I want to optionally wrap the title in a link (the same component is used in more than one place), and would appreciate guidance for the best way to do it.
My component looks like this:

var FeedItem = React.createClass({
renderRawMarkup: function(text) { ... },
render: function() {
var item = this.props.item,
rawBody = this.renderRawMarkup(item.body);

return (
<article className="feed-item">
<h2 className="feed-item__title">{item.title{</h2>
<div className="feed-item__body" dangerouslySetInnerHTML={rawBody} >

Am I best to create a new component just for the title? Or can I use an if inside the return, e.g.:

<h2 className="feed-item__title">
{if (item.path) { <a href={item.path}> }}
{if (item.path) { </a> }}

I'm a bit of a React novice so apologies if I'm approaching the problem from completely the wrong angle!

Answer Source

You can't use if statements inside jsx, but you can make use of ternary expressions. In your case, you can use:

<h2 className="feed-item__title">
  { item.path ? <a href={item.path}>{item.title}</a> : {item.title} }

This is stated in the official documentation: React docs