Import SVG as ReactComponent with dynamic()
Answered
Barbado da Terceira posted this in #help-forum
Barbado da TerceiraOP
Hello everyone !
I would like to dynamically import SVG in a List component to display icons based on a dynamic name fetched from my CMS's content.
I already imported static SVGs as ReactComponent to display them directly and get them in the DOM as follow
But, when I try to import my SVG dynamically, like below
I get the following error
It seems logic as my component is not imported as ReactComponent, but I have no idea on how to bypass it..
I looked multiple subjects on StackOverflow, but nothing seems to work.
I also use
I would like to dynamically import SVG in a List component to display icons based on a dynamic name fetched from my CMS's content.
I already imported static SVGs as ReactComponent to display them directly and get them in the DOM as follow
import { ReactComponent as Hamburger } from '@img/icons/hamburger.svg'But, when I try to import my SVG dynamically, like below
import dynamic from 'next/dynamic'
interface LazySvgProps extends React.ComponentProps<'svg'> {
name: string
}
const LazySvg: React.FC<LazySvgProps> = async ({ name, ...props }) => {
const Svg = dynamic(() => import(`@img/icons/${name}.svg`))
return <Svg {...props} />
}
export default LazySvgI get the following error
InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('data:image/svg+xml;base64,PHN2Zy[...]') is not a valid name.It seems logic as my component is not imported as ReactComponent, but I have no idea on how to bypass it..
I looked multiple subjects on StackOverflow, but nothing seems to work.
I also use
@svgr/webpack in my next.config.mjsAnswered by Barbado da Terceira
I found a solution, I needed to specify
I don't know why, but I couldn't do it directly on the Svg like
ReactComponent property in the return of import() const Svg = dynamic(() => import(`@img/icons/${name}.svg`).then((icon) => icon.ReactComponent))I don't know why, but I couldn't do it directly on the Svg like
Svg.ReactComponent1 Reply
Barbado da TerceiraOP
I found a solution, I needed to specify
I don't know why, but I couldn't do it directly on the Svg like
ReactComponent property in the return of import() const Svg = dynamic(() => import(`@img/icons/${name}.svg`).then((icon) => icon.ReactComponent))I don't know why, but I couldn't do it directly on the Svg like
Svg.ReactComponentAnswer