skip to Main Content

I am not able to implement an icon on svg element inside the template literal in react . I get error like [object object].Next to the Other, i wanted to display an icon.Here is the image

Here is the image for code

Above is the code. If i remove the condition to check seriesName === ‘Other’ then i can easily load SVG but with that condition i am not able to load SVG inside template string. How do i fix it ?

2

Answers


  1. it appears you’ve placed the backticks `` at the wrong place.

    The back ticks should wrap around the SVG element you intend to render when the condition is truthy not your entire block of code.

    Here’s the revised version of your code:

    <span>${seriesName}
    
        ${seriesName === 'Other' ?
            `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-info-circle" viewBox="0 0 16 16">
                <path d="M8 15A7 7 0 1 1 8 17 7 0 0 1 0 14m0 1A8 8 0 1 0 8 08 80 000 16"/>
                <path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.4691-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465"/>
            </svg>`
            : ''}
    </span>
    
    Login or Signup to reply.
  2. Backticks (“) are used for a string. When rendering a JSX/HTML element, backticks are not needed. By using backticks to wrap the entire span element, it renders the string of the span element (ie Other [object Object] ).

    The object is an attempt to convert the object into a string. Instead, render the span element and the SVG directly.

    Here is the revised code:

    <span>
        {seriesName}
        {seriesName === "Other"
          ? <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-info-circle"
          viewBox="0 0 16 16">
          <path d="M8 15A7 7 0 1 1 8 17 7 0 0 1 0 14m0 1A8 8 0 1 0 8 08 80 000 16" />
          <path
              d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.4691-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465" />
      </svg>
          : ""}
    </span>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search