Skip to content

Commit

Permalink
Add support for a per-view custom alt tag (#370)
Browse files Browse the repository at this point in the history
* Add support for a per-view custom alt tag

* Add documentation for advanced source props

* Update README to document ReactNode captions

* Check for non-string alt tags and error

* Add a warning for images with a complex caption but no alt tag
  • Loading branch information
zackdotcomputer authored May 14, 2020
1 parent 5cb5680 commit 9b34b3e
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,28 @@ class Component extends React.Component {
}
}
```

### Advanced Image Lists

The simplest way to define a list of images for the carousel looks like:

```jsx
const images = [{ source: 'path/to/image-1.jpg' }, { source: 'path/to/image-2.jpg' }];
```

However, react-images supports several other properties on each image object than just `source`. For example:

```jsx
const image = {
caption: "An image caption as a string, React Node, or a rendered HTML string",
alt: "A plain string to serve as the image's alt tag",
source: {
download: "A URL to serve a perfect quality image download from",
fullscreen: "A URL to load a very high quality image from",
regular: "A URL to load a high quality image from",
thumbnail: "A URL to load a low quality image from"
};
}
```

All these fields are optional except `source`. Additionally, if using an object of URLs (rather than a plain string URL) as your `source`, you must specify the `regular` quality URL.
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export interface TrackProps {

export interface ViewType {
caption?: React.ReactNode;
alt?: string;
source: string | {
download?: string;
fullscreen?: string;
Expand Down
25 changes: 24 additions & 1 deletion src/formatters.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,30 @@ function getFullscreenLabel({ isFullscreen }: FullscreenProps): string {

/* alt text for each image in the carousel */
function getAltText({ data, index }): string {
if (data.caption) return data.caption;
if (data.alt) {
if (typeof data.alt !== 'string') {
console.error(
`Image ${
index + 1
} had a non-string alt property, which will probably render incorrectly.\nInstead of a plain string it was `,
data.alt
);
}

return data.alt;
}

if (data.caption) {
if (typeof data.caption !== 'string') {
console.warn(
`Image ${
index + 1
} has a non-string caption, but no alt value provided. This will probably make the alt prop unintelligible for screen readers. Is this intentional?`
);
}

return data.caption;
}

return `Image ${index + 1}`;
}
Expand Down

0 comments on commit 9b34b3e

Please sign in to comment.