gregberge / svgr

Transform SVGs into React components 🦁
https://react-svgr.com
MIT License
10.58k stars 421 forks source link

fallback title is not working #943

Open AnweshGangula opened 9 months ago

AnweshGangula commented 9 months ago

🐛 Bug Report

The documentation says that

...If titleProp is set to true and no title is provided (title={undefined}) at render time, this will fallback to an existing title element in the svg if exists.

But, setting titleProp: true in Next.js webpack doesn't add title even if the SVG itself has a title element in it.

Note that I'm using typescript in my project

To Reproduce

  1. Create a Nextjs project and configure SVGR in it

    config.module.rules.push({
        test: /\.svg$/i,
        issuer: /\.[jt]sx?$/, // { not: /\.(css|scss|sass)$/ },
        resourceQuery: /svgr/, // only use svgr to load svg if path ends with *.svg?svgr
        use: [{
            loader: "@svgr/webpack",
            options:{
                titleProp: true, // default is false
                descProp: true, // default is false
    
            }
        }],
    });
  2. Create an SVG with <title> element in it
  3. import the ReactSvgImport into any component in React import SVG from './../abc.svg?svgr
  4. Use the imported SVG in React JSX <ReactSvgImport />

Expected behavior

The resultant SVG in DOM should fallback to the existing title element from the root SVG

AnweshGangula commented 9 months ago

I tried this out in the Playground and noticed that the resultant TSX doesn't consider titleId as an optional property. Could this be an issue?

<title id={titleId}>{"Rectangle 5"}</title>

import * as React from "react"
import { SVGProps } from "react"
interface SVGRProps {
  title?: string;
  titleId?: string;
}
const SvgComponent = ({
  title,
  titleId,
  ...props
}: SVGProps<SVGSVGElement> & SVGRProps) => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width={48}
    height={1}
    title="abc"
    aria-labelledby={titleId}
    {...props}
  >
    {title === undefined ? (
      <title id={titleId}>{"Rectangle 5"}</title>
    ) : title ? (
      <title id={titleId}>{title}</title>
    ) : null}
    <path fill="currentColor" fillRule="evenodd" d="M0 0h48v1H0z" />
  </svg>
)
export default SvgComponent