Styling and alt-ing a SVG React component

Viewed 764

I'd like to import an svg image, style it using classes and provide alt text to make it accessibile. I'm not sure how to do it.

import { default as LogoSrc, ReactComponent as Logo } from "./logo.svg";

const svgTag = () => {
  // this produces html: <svg class='someClass'/>
  // alt is not visible  
  return <Logo className='someClass' alt='logo'/>  
}
const imgTag = () => {
  // this produces <img src="logo.svg" alt='logo' class='someClass'/>  
  // svg is not styled
  return <img src={LogoSrc} alt="logo"  class='someClass'/>
}
1 Answers

When inlining an SVG (your "svgTag" option) you can't use the alt attribute without giving it a role="img".

However there is an even better way to add text for screen readers on an SVG.

SVGs have the <title> attribute (think of that like alt on an image) and the <desc> attribute to provide a lot more detail about the image.

There is a great article by Carie Fisher on accessible SVGs

The pattern that seems to win out is:

<svg role="img" aria-labelledby="svg1Title" class="someClass">
   <title id="svg1Title">Logo</title>
   [SVG paths etc.]
</svg>

So this is ultimately what you need your <Logo component to produce!

So if you use your first option (so you can style with CSS within the document, you can't do that with option 2) and then adjust the SVG to contain a <title> and the aria-labelledby pointing to the ID of that title you will have what you need.

The key bit is that your alt is essentially now <title> and you link that title to the SVG using aria-labelledby just to improve compatibility.

In React

Getting such html output from react should be possible with

<Logo title='accessible Logo title'/>

since React 3.1

Related