简体   繁体   中英

How to href Link only one element of a .map array inside JSX

I just want to have a link for id = 0, and no hyperlinks for the rest of the elements in the projects array. Can someone please help, thanks :)

const Projects = () => (
  <Section nopadding id="projects">
    <SectionDivider />
    <SectionTitle main>Projects</SectionTitle>
    <GridContainer>
      {projects.map(({ id, image, title, description, tags, source, visit }) => (
        <BlogCard key={id}>
          <Img src={image} />
          <Link href="/campaigns"> 
          <TitleContent>
            <HeaderThree title>{title}</HeaderThree>
            <Hr />
          </TitleContent>


............

...........
);

Try the below solution

<GridContainer>
  {projects.map(({ id, image, title, description, tags, source, visit }) => {
    const linkProps = id === 0 ? { href: "/campaigns" } : {}
    return (
      <BlogCard key={id}>
        <Img src={image} />
        <Link {...linkProps}>
          <TitleContent>
            <HeaderThree title>{title}</HeaderThree>
            <Hr />
          </TitleContent>
        </Link>
      </BlogCard>
    )
  })}
</GridContainer>

if you need that link even without herf use this code

 <GridContainer>
      {projects.map(({ id, image, title, description, tags, source, visit }) => {
        const linkProps = id === 0 ? { href: "/campaigns" } : {href: ""}
        return (
          <BlogCard key={id}>
            <Img src={image} />
            <Link {...linkProps}>
              <TitleContent>
                <HeaderThree title>{title}</HeaderThree>
                <Hr />
              </TitleContent>
            </Link>
          </BlogCard>
        )
      })}
    </GridContainer>

if you don't need that link it doesn't have href use this code

<GridContainer>
      {projects.map(({ id, image, title, description, tags, source, visit }) => {
        const linkProps = id === 0 ? { href: "/campaigns" } : ''
        return (
          <BlogCard key={id}>
            <Img src={image} />
           {linkProps!=''&& <Link {...linkProps}>
              <TitleContent>
                <HeaderThree title>{title}</HeaderThree>
                <Hr />
              </TitleContent>
            </Link>}
          </BlogCard>
        )
      })}
    </GridContainer>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM