reactjssvgaccessibilitysvgr

Passing title to svg using vite-plugin-svgr


I'm trying to pass a title to and <svg> using vite-plugin-svgr and I can't find a way to do it. I know that the <svg> itself doesn't have a title attribute and that in order to pass title to <svg> I need to pass <title> element as the first child. What is the best way to achieve that without using ref ?

How I tried to pass the title (this doesn't work):

import { ReactComponent as Icon} from "./icon.svg";
...
return <Icon title="icon title" />

I also tried passing a <title> element using React.cloneElement() but that doesn't seem to work either:

import { ReactComponent as Icon} from "./icon.svg";
...
return cloneElement(<Icon />, undefined, <title>icon title</title>);

example:

<!-- circle.svg -->

<svg height="100" width="100" xmlns="http://www.w3.org/2000/svg">
  <circle r="45" cx="50" cy="50" fill="red" />
</svg>
// Icon.jsx
import { ReactComponent as Circle } from "./assets/circle.svg"

const Icon = () => {
    return (
        <div>
            <Circle title='icon title' />
        </div>
    );
};

Final DOM :

<svg height="100" width="100" xmlns="http://www.w3.org/2000/svg" title="icon title">
    <circle r="45" cx="50" cy="50" fill="red"></circle>
</svg>

Solution

  • Passing title is not enabled by default using vite-plugin-svgr, in order to pass the title you in the svgr config you need to set the titleProp to be true like so:

    svgr({
      svgrOptions: {
        titleProp: true,
      },
    });
    

    That way when the svgr transforms the title attribute into a <title> tag.