Import animated SVG files in Next.js 13
import Image from "next/image"; export default function Home() { return ( <main className="flex h-screen flex-col items-center"> <div className="container mt-12 flex flex-col items-center justify-center gap-4 px-4 py-8"> <object type="image/svg+xml" data="/images/blaze-hero-animation.svg"> svg hero animation </object> </div> <Image src="/images/blaze-hero-animation.svg" alt="hero animation" width={500} height={500} /> </main> ); }
The object tag gives me an animated svg, but with a white background color (the original svg had a transparent background. The image gives me a transparent svg, but without any animation. Do I need to use SVGR or something else? This is in Next.js 13.
I only want to import my transparent animated svg files. id don't want to mess with SVGR because I don't think I should be using it.
P粉1214472922024-03-28 09:01:30
You can create a React component to wrap your SVG like this:
//LinkArrowIcon.tsx type Props = { className?: string; }; export function LinkArrowIcon({ className, ...props }: Props) { return ( <svg xmlns="http://www.w3.org/2000/svg" width={24} height={24} viewBox="0 0 24 24" className={`w-full h-auto ${className}`} {...props} > <path fill="none" d="M0 0h24v24H0z" /> <path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-5m-7 1L20 4m-5 0h5v5" /> </svg> ); }
//Home.tsx import LinkArrowIcon from "./LinkArrowIcon"; export default function Home() { return ( <main className="flex h-screen flex-col items-center"> <div className="bg-dark dark:bg-light text-light dark:text-dark"> <LinkArrowIcon className="w-6 h-auto" /> </div> </main> ); }
Here I'm using Tailwind CSS combined with a theme to determine whether the SVG should use a light or dark color (-light
and -dark
are just custom colors).
Also check out the React SVGR website which automatically converts SVG into React components.
Notice
I'm having trouble using Typescript to run next build
on some SVGs that have tags like
within the body.
I tried different solutions but none seemed to work so I just replaced the file extension from .tsx
to .jsx
and the build went fine.