I have a const
const tags = [
{
tagName: "tag1",
tagLink: "#"
},
{
tagName: "tag2",
tagLink: "#"
},
{
tagName: "tag3",
tagLink: "#"
}
];
I want to use map function to render anchor tag and also I want a separator | in between the anchor tags.
I tried using join but then it doesn't work.
Please check the fiddle
map using join
<div style={style}>
{tags
.map((tag, i) => (
<a href={tag.tagLink} alt="">
{tag.tagName}
</a>
))
.join("|")}
</div>
Produces: [object Object]|[object Object]|[object Object]
Could you render "|" in map function? Like I wrote in the comment, using join on JSX Object coerce it to String, which results in [object Object].
{tags.map((tag, i) => (
<a href={tag.tagLink} alt="">
{tag.tagName} {i < tags.length - 1 ? "|" : ""}
</a>
))}
You are trying to use "join" elements of an array of elements. It will internally typecast the elements into a string which for any object comes as [object Object]. Hence, you are getting [object Object]|[object Object]|[object Object]
Something like this will work:
{tags.map((tag, i) => {
return <span>
<a href={tag.tagLink} alt="">
{tag.tagName}
</a> {i < tags.length - 1 ? "|" : null}
</span>
})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With