How to conditionally include a tag in the middle of some HTML in React
I have a Avatar
React component and it is possible to link it to a profile or not. You might not want it to link to a profile if, say, your user profile and you want to create a custom one instead clickHandler
. Is there a better way other than just doing an if / else with basically identical HTML in every, if not just a link? Below is some rendering code 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>
+3
source to share
2 answers
Using:
<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 the double definition of img by specifying it earlier:
var img = <img className="__avatarimage" src={this.props.user.avatar} />;
and insert it using:
{img}
+3
source to share
I would create a function that returns an image, or an image wrapped in a link, and then add it to a div.
var createAvatar = function() {
if (this.props.link) {
return <Link to="profile" params={{userId:this.props.user.id}}>
<img className="__avatarimage" src={this.props.user.avatar} />
</Link>;
} else {
return <img className="__avatarimage" src={this.props.user.avatar} />;
}
};
var avatar = createAvatar();
return <div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}>
{avatar}
</div>;
+1
source to share