Display a placeholder if image source is not working or missing

Looking to display a logo in next.js, my plan is to show a span if the logo is not available and hide it if it is.

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

I managed to hide the image using the CSS rule below. Now I want to display the span content when the image is empty, and show the image when it's not empty.

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

Any suggestions on how to achieve this?

Answer №1

To achieve this, you can utilize CSS alongside a basic JavaScript function.

Begin by setting up the CSS with a sibling selector:

.logo span {
  display: none;
}
.logo img.hidden {
  display: none;
}
.logo img.hidden + span {
  display: block;
}

Next, apply this script to the image elements.

let logos = document.querySelectorAll(".logo img");
for (logo of logos) {
  logo.onerror = () => {
    this.classList.Add("hidden");
    this.onerror = null;
  }
}

Answer №2

To incorporate images in your Next.js project, you need to import Image from 'next/image'.

Check out the official documentation for more information

After that, make sure to implement the following code:

<div className='logo'>
   <Link href="#">
      <Image src="#" alt="Placeholder" unsized />
   </Link>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adjusting the maximum height of the column panel within the DataGrid element

I'm trying to adjust the max-height of a column panel that opens when clicking the "Columns" button in the Toolbar component used in the DataGrid. I am working with an older version of @material-ui/data-grid: "^4.0.0-alpha.8". https://i.stack.imgur.c ...

Modifying object properties in JavaScript

Looking to update a boolean attribute for an object in JavaScript (in this case, the object is part of fullPage.js library). I am interested in turning off the navigation attribute by setting it to false, and ideally would like to do this from a separate f ...

Using the Vercel App Domain as the primary web domain for a Facebook application

https://i.sstatic.net/ayA1p.png Hey there, I've got a vercel app up and running on the domain. However, I'm facing an issue when trying to integrate it with my Facebook app. For some reason, Facebook doesn't allow me to add any vercel doma ...

The Apollo client's GraphQL query encountered an unforeseen termination of the JSON input stream

I have customized my NextJS site with WP WooCommerce integration. By default, the query result only returns up to 100 items, but I have increased it to 1000 without any issue. When I send a request with a query like this: query MyQuery { products(fir ...

Exploring the process of extracting XML data from the body within a Next.js API route

I'm currently using PrimeReact 8.5 fileUpload along with Next.js 12.3. How can I extract only the XML data sent from PrimeRact? Here is how I upload the file: <FileUpload name="edcStock" url="/api/admin/edcup ...

Solution for fixing the position of a div scrollbar under the browser scrollbar

When working on my web app, I faced an issue with a fixed div modal that takes up the entire screen. The problem is that the scrollbar for this modal is not visible, only the body scrollbar can be seen. It seems like the fixed div's scrollbar is posit ...

Hidden Navigation Bar in AngularJS

Is there a way to hide the navBar when the route is "/"? I managed to successfully hide/show the navbar, but the issue arises when the navbar is hidden. The "app-body" div then has 50px of padding top (where the navbar should be). Here is my HT ...

Is there a way to change the button design within the CSS code of Mailchimp's embed feature?

Struggling to customize the button style and positioning in Mailchimp's embed CSS: <!-- Begin Mailchimp Signup Form --> <link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/c ...

Explain the inner workings of the setTimeout() function in JavaScript

My goal is to create a line in my code by placing points according to the line equation and adding a 100 millisecond delay before each point is displayed. However, when I try to run the code, it seems to wait for some time and then displays all the points ...

Uncertainty surrounds the interaction of computed height and margins with CSS float right

What is the reason behind this HTML code: <html> <head> <style type="text/css"> .left { background-color: yellow; } .right { float: right; background-color: lightgray; width: 150px; } </sty ...

Not defined: The situation arises when I am retrieving data from GraphQL within a Next.js environment

I'm currently exploring how to fetch data from graphql in Next.js. Strangely, when I try to do so, it returns undefined. Surprisingly, it works perfectly fine in the playground but encounters an issue on Next.js. Check out the graphql API here: http ...

Is there a way to display two cards side by side in mobile view?

On a desktop view, 2 cards are displayed in a row. I would like them to also appear in a row on mobile view. I tried using col-sm-4 but it's not working. How can I get the cards to display in a row on mobile view so that I can see both the product pho ...

Setting distinct fonts for input placeholder and value: A guide

Can different fonts be set for an input placeholder and value? I have a scenario where the input placeholder is in a right-to-left language while the value is in English. Is it achievable using CSS3? ...

What is the best way to showcase a Table and an Image side by side in HTML using inline

Can someone help me figure out how to align my image and table on the same level? I've been struggling to get "inline-block" to work. :( <p id="play"> hey </p> <div id="menu"> <table> <tr> <td>Models</td& ...

How can I ensure that my content stays fixed at the bottom of a scrolling div in Material UI React?

I have developed a React JS component using Material UI that includes a chat input feature. However, I am facing an issue where the width of the chat input is always half the screen size on desktop or mobile devices. When I try to change the width to 100%, ...

What could be causing my select element to not display any options after being dynamically generated using JavaScript?

function createDropdown() { const selectElement = document.createElement('select'); selectElement.setAttribute('type', 'text') toolresult.appendChild(selectElement); const optionElement = document.createElement('o ...

"Embracing seamless global expansion with Clerk and Next-Intl

I recently came across a discussion on the clash between Next.js Clerk and NextIntl Middleware, which can be found here After testing the integration of next-intl and clerk v5, I encountered an issue where accessing the /api folder resulted in a 404 error ...

Select Box in HTML now supports the addition of a Background Image, enhancing

Currently, I am trying to customize the select option box using HTML and CSS. My main goal is to incorporate a scroll feature into the option box. However, I have encountered an issue where the image of the checked box remains visible on the screen. Below ...

Expanding on the specific properties of a parent component to its child, using SASS's extend feature

Can selected or specific properties be shared/extended from the parent to the child without the need to create a variable? .main-container { padding: 20px; margin: 20px; ul { padding:$parentPadding(); margin: 0; } ...

What is the proper way to implement SWRConfig with server-side rendering in Next.js?

After reviewing the documentation and exploring how to integrate it with Next.js SSR, I find myself struggling to grasp the implementation process. None of the methods I can think of seem logical. A recent discussion on Stack Overflow suggested that initi ...