How do I conditionally include a tag in the middle of some HTML in React

javascript, reactjs, syntax

Solution

Use:

<div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}>
{ this.props.link ?
  <Link to="profile" params={{userId:this.props.user.id}}>
    <img className="__avatarimage" src={this.props.user.avatar} />
  </Link>
  : <img className="__avatarimage" src={this.props.user.avatar} /> }

You can try to eliminate double definition of img by defining it earlier:

var img = <img className="__avatarimage" src={this.props.user.avatar} />;

and embed it using:

{img}

Problem

I have an `Avatar` React component and there's an option to make it link to a profile or not. You may not want it to link to a profile if, say, your on the users profile and instead you want to do a custom `clickHandler`. Is there a nicer way other than just doing an if/else with basically identical HTML in each if and else other than a link? Below is some pseudo rendering code just to show an example of what I mean: ``` <div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}> {if (this.props.link) { <Link to="profile" params={{userId:this.props.user.id}}> } } <img className="__avatarimage" src={this.props.user.avatar} /> {if (this.props.link) { </Link> } } </div> ```

Original source