Valid ALT

Addy Osmani tweeted the other day the following:

Tip: highlight images missing alt text with img:not([alt]) pic.twitter.com/zgjdE5iTU6

— Addy Osmani (@addyosmani) February 2, 2020

This left me thinking, this only provides insight into examples of when the `alt` attribute is missing altogther, but what about use cases for examples in React when the alt text is present and not containing any information. Yes, you are correct in saying this is a valid use case if the image is for decorative, but what about the cases where you are using a component that is setup to output the value based on a property passed in from another component. We can also provide insight into images that are on the page that have an alt attribute but does not contain a value. By adding a small helper in our CSS we can provide a user with a "warning" of images that have alt but no value, so they are able to quicky see if that's correct behaviour for a given image.

By providing a warning style, below you will see an orange border around images that have an alt attribute but no value we can quickly identify what is known as decorative images, and then see if they are all decorative images.

For example in a web application where a developer is using a utility function to display and image/graphic and assumes the alt text is being set based on them passing a value, or even if they are just passing an object of data from a API or other datasource. Example of a CMS, where the UI is built in React and you just pass the image data from the API into your component - the issue here is you are hoping the admin/editor added the alt text in the photo/media library tool.

See the example below, showing how the utility function is set up so the alt value defaults to a blank string. If an API key is missing this accounts for that and will not cause issues.


Code Example

			
// Simple Image Component
const Image = ({src, alt=""}) => <img src={src} alt={alt} />


// example payload from an API/Datasource
const imageObject = {
	src: 'https://picsum.photos/id/233/200/200',
	alt: '',
};

// Passing the payload straight to the component for rendering
<Image {...imageObject} />
		

CSS

			
// Error - missing alt
img:not([alt]) {
	border: 5px solid rgb(255, 0, 0);
}

// Warning - Has alt attribute but no text value
img[alt=''] {
	border: 5px solid rgb(255, 165, 0);
}

React Demo