Skip to content

How to render SVG based off of a ternary operator

I’m trying to setup a ternary operation to either show a SVG inside of an a tag or not based off of whether a link is present or not. I’m using Sanity to pull the links from.

<a href={project.link} class="z-10" rel="noopener noreferrer" target="_blank">
    <svg> img code here... </svg>                        
</a>

In plain english…if the project contains a link, render the SVG link to the project

What I tried but didn’t work:

<a className={`${project.link ? "" : "none"}`} href={project.link} class="z-10" rel="noopener noreferrer" target="_blank">
    <svg> img code here... </svg>                        
</a>

My question is, what do I put as the first condition if I want to render the SVG?

Answer

I am making some assumptions about the blanks in your question, so please feel free to correct me.

The first option is to only show the entire block if project link is set.

{project.link ? <a className.......><svg></svg></a> : null}

Or simply use the same ternary condition for the SVG, as such:

<a className.....>
   {project.link ? <svg>...</svg> : null}
</a>