Skip to content

Commit

Permalink
Adding altPlaceholder for changing the alt attribute on error.
Browse files Browse the repository at this point in the history
  • Loading branch information
erinesullivan committed Nov 13, 2024
1 parent fab07c4 commit ba5a953
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
10 changes: 6 additions & 4 deletions src/modules/browse/components/ShelfBrowseCarousel/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,12 @@ const ShelfBrowseCarousel = ({ callNumber, items, itemsPerPage, setButtonAction,
<>
<dt className='visually-hidden'>Book cover</dt>
<dd className='item-term-book_cover'>
<ImagePlaceholder
src={bookCover(item)}
alt={`The cover of ${item.title}`}
index={trueIndex}
<ImagePlaceholder {...{
alt: `The cover of ${item.title}`,
altPlaceholder: `Placeholder image for ${item.title}`,
index: trueIndex,
src: bookCover(item)
}}
/>
</dd>
</>
Expand Down
17 changes: 10 additions & 7 deletions src/modules/reusable/components/ImagePlaceholder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,33 @@ import './styles.css';
import React, { useState } from 'react';
import PropTypes from 'prop-types';

const ImagePlaceholder = ({ alt, index, src, ...rest }) => {
const [imageState, setImageState] = useState('loading');
const ImagePlaceholder = ({ alt = '', altPlaceholder = '', index = 0, src = '', ...rest }) => {
const [imgState, setImgState] = useState('loading');
const [imgSrc, setImgSrc] = useState(src);
const [imgAlt, setImgAlt] = useState(alt);

const handleImageLoad = () => {
setImageState('settled');
setImgState('settled');
};

const handleImageError = () => {
// Choosing between 15 placeholder images based on the index's remainder
setImgSrc(`/placeholders/placeholder-${index % 15}.svg`);
setImageState('settled');
setImgState('settled');
setImgAlt(altPlaceholder);
};

return (
<>
<img
src={imgSrc}
alt={alt}
alt={imgAlt}
onLoad={handleImageLoad}
onError={handleImageError}
style={{ display: imageState === 'settled' ? 'block' : 'none' }}
style={{ display: imgState === 'settled' ? 'block' : 'none' }}
/>

{imageState === 'loading' && (
{imgState === 'loading' && (
<div
className='image-placeholder placeholder margin-bottom__none'
{...rest}
Expand All @@ -40,6 +42,7 @@ const ImagePlaceholder = ({ alt, index, src, ...rest }) => {

ImagePlaceholder.propTypes = {
alt: PropTypes.string,
altPlaceholder: PropTypes.string,
index: PropTypes.number,
src: PropTypes.string
};
Expand Down

0 comments on commit ba5a953

Please sign in to comment.