I have a component that will sometimes need to be rendered as an <anchor>
and other times as a <div>
. The prop
I read to determine this, is this.props.url
.
If it exists, I need to render the component wrapped in an <a href={this.props.url}>
. Otherwise it just gets rendered as a <div/>
.
Possible?
This is what I'm doing right now, but feel it could be simplified:
if (this.props.link) {
return (
<a href={this.props.link}>
<i>
{this.props.count}
</i>
</a>
);
}
return (
<i className={styles.Icon}>
{this.props.count}
</i>
);
UPDATE:
Here is the final lockup. Thanks for the tip, @Sulthan!
import React, { Component, PropTypes } from 'react';
import classNames from 'classnames';
export default class CommentCount extends Component {
static propTypes = {
count: PropTypes.number.isRequired,
link: PropTypes.string,
className: PropTypes.string
}
render() {
const styles = require('./CommentCount.css');
const {link, className, count} = this.props;
const iconClasses = classNames({
[styles.Icon]: true,
[className]: !link && className
});
const Icon = (
<i className={iconClasses}>
{count}
</i>
);
if (link) {
const baseClasses = classNames({
[styles.Base]: true,
[className]: className
});
return (
<a href={link} className={baseClasses}>
{Icon}
</a>
);
}
return Icon;
}
}
const baseClasses =
into thatif (this.props.link)
branch. As you are using ES6, so you can also simplify a bit byconst {link, className} = this.props;
and then usinglink
andclassName
as local variables.