I have a component which is wrapped in an anchor link and has hover styling. I need to be able to conditionally render the channel.url
link on the div if there is an available url in the data for the particular element that has been looped through.
I tried checking if the length of the channel.url
is greater than 0, but my logic wasn't working. In the end, it should simply be that if the particular item that's looped through doesn't have a url in its data object, it will simply not have the anchor link applied to it.
<ul>
{items.children.map((channel, i) => (
(channel, i) =>
channel.url ? (
<a href={channel.url} target="_blank">
<FeaturedApps />
</a>
) : (
<FeaturedApps />
)
)}
))}
</ul>
UPDATE
I got the logic working, thanks to Ethan. Trying to clean it up thought and move the li to its own component but having an issue passing icon
in.
COMPONENT
const FeaturedApps = ({ iconName, className }) => {
<li>
<IconForChannel iconName={channel.icon} className={classes.icon} />
<span className={classes.channelName}>
{channel.name}{" "}
<Icon className={classes.nameIcon} name={channel.nameicon} size={12} />
</span>
</li>;
};
LOOP WITH LOGIC
<ul>
{items.children.map((channel, i) => (
(channel, i) =>
channel.url ? (
<a href={channel.url} target="_blank">
<FeaturedApps />
</a>
) : (
<FeaturedApps />
)
)}
))}
</ul>
You could save the 'inner' part to a variable and render conditionally, ie
<ul>
{items.children.map((channel, i) => {
let inner = (<span className={classes.channelName}>
{channel.name}
</span>);
return (
<li key={i}>
{ (channel.url ? (<a href={channel.url} target="_blank">{inner}</a>) : inner) }
</li>
</a>
)};
)}
</ul>
it was mentioned above that li should always be the direct child of ul, and I've adjusted that also while at it. Hope this is helpful.
This may work:
<ul>
{items.children.map((channel, i) => (
(channel.url) ?
<a href={channel.url} target="_blank">
<li key={i}>
<span className={classes.channelName}>
{channel.name}
</span>
</li>
</a>
:
<li key={i}>
<span className={classes.channelName}>
{channel.name}
</span>
</li>
))}
</ul>
This ternary operator is saying: "for each channel, if that channel has a url as a property, render that list item wrapped in the channel.url as an anchor link, else, simply render the list item."
condition ? expr1 : expr2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.