skip to Main Content

Hello I am trying to show a logo in next.js, my idea is to show a Span if the logo is not available and if it is it hides it.

<div className='brand'>
  <Link href="#">
    <img src="#" alt="UnSet" />
    <span>UnSet</span>
  </Link>
</div>

I tried this and it hides the image, now I want to achieve that if the image is empty it shows the span content and if not it shows the image.

.brand a img[src]{
  display: none;
}

Any ideas on how to do this?

2

Answers


  1. You can use some css and a simple JavaScript function to accomplish this.

    Setup the CSS using a sibling selector:

    .brand span {
      display: none;
    }
    .brand img.unset {
      display: none;
    }
    .brand img.unset + span {
      display: block;
    }
    
    

    Then add this to the image objects.

    let images = document.querySelectorAll(".brand img");
    for (i of images) {
      i.onerror = () => {
        this.classList.Add("unset");
        this.onerror = null;
      }
    }
    
    Login or Signup to reply.
  2. You should import Image from 'next/image'.

    Reference

    Then,

    <div className='brand'>
       <Link href="#">
          <Image src="#" alt="UnSet" unsized />
       </Link>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search