1

I have a nextJs app with some SVG images that are imported as components using SVG.

How can I make these images accessible? Is there a way to add an alt attribute?

Jay Patel
  • 1,098
  • 7
  • 22
  • Why are you using `svgr`? Next.js already has an `Image` component that you can use, which you can mention dimensions, fill style and alt. – nick Oct 06 '21 at 07:27
  • Does this answer your question: [Alt tag possible for inline SVG?](https://stackoverflow.com/questions/23146570/alt-tag-possible-for-inline-svg)? You should use the [``](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/title) element. – juliomalves Oct 07 '21 at 07:19

1 Answers1

1

When you talk about making a component accessible, you want to consider both how that component is presented to users (i.e. its label, description, role, and any value associated with the component) and whether it is keyboard accessible.

Since you're asking about adding an alt attribute (or equivalent) to an <svg> component, I take it you're only looking to label the <svg> for screen readers. You can do this by adding a <title> tag with text inside any <svg> container element. The text inside the <title> tags won't be visible but will be displayed as a tooltip.

For example:

<svg viewBox="0 0 20 10" xmlns="http://www.w3.org/2000/svg">
    <circle cx="5" cy="5" r="4">
        <title>I'm a circle</title>
    </circle>
    <rect x="11" y="1" width="8" height="8">
        <title>I'm a square</title>
    </rect>
</svg>

If there is already text on the page that labels the <svg>, then you can reference this element by using the aria-labelledby attribute on the <svg> tag.

See here: <title> — the SVG accessible name element

George Chapman
  • 462
  • 2
  • 9