Created by: sudkumar
Fixes #7103 (closed) Add title to SVG component.
Native svg element doesn't accept a title prop. It requires a <title>
children. Currently in CRA SVG component, we don't have an option to add a title for our SVG components. This PR enable us to add a title element by providing a title
prop to SVG components.
import { ReactComponent as Logo } from "./logo.svg"
function App () {
return <Logo title="Application Logo" />
}
renders
<svg ...>
<title>Application Logo</title>
We are using svgr's titleProp option to inject a title element for our SVG components. If no title is provided to the SVG component at render time, this SHOULD fallback to svg's title element.
I have tested it on my local machine by creating a new application with yarn create-react-app my-app
(after reading contribution instructions) and it is working as expected for logo.svg
file in our template.
Why WIP
We are waiting for https://github.com/smooth-code/svgr/pull/311 to get merge to avoid affecting existing code bases which might have title element inside there svg files because, the current behaviour of svgr's titleProp
option is to render/replace any title in an svg with an element that only renders the title provided by the prop.
For example: Given our svg file
<svg ...>
<title>Logo</title>
..
if we set titleProp
to true, it will return an SVG component as
function SVG ({ title, ...attrs }) {
return <svg ... {...attrs}><title>{title}</title>....
}
Which is not what we want because it will not fallback to the default title for svg. What we want is, when the above svg file gets processed by svgr, the output should be:
function SVG ({ title, ...attrs }) {
return <svg ... {...attrs}><title>{typeof title === "undefined" ? 'Logo' : title}</title>....
}
And so we are waiting for that PR (on svgr) to get merged before we proceed on this PR.