Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a separator using map function

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]

like image 684
Rickie Avatar asked Mar 21 '26 06:03

Rickie


2 Answers

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>
))}
like image 142
matvs Avatar answered Mar 23 '26 20:03

matvs


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>           
})}
like image 41
amulous Avatar answered Mar 23 '26 20:03

amulous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!