Docs
SVGM.tsx

SVGM.tsx

The main component from which you will import all of your .svg files.

The installation script svgm-setup scaffolds the SVGM.tsx component into your project for you to start using right away.

SVGM.tsx
import React, { Suspense } from 'react';

export interface SVGMProps {
    kind: string;
    className?: string;
}
                        
const importAll = (requireContext: { keys: () => string[]; (path: string): any; }) => {
    return requireContext.keys().reduce<{ [key: string]: React.ComponentType<any> }>((acc, next) => {
        const key = next.replace(/^.*[\\/]/, '').replace(/\.\w+$/, '');
        acc[key] = requireContext(next).default;
        return acc;
    }, {});
};
                        
const iconFiles = importAll(require.context('/', false, /\.svg$/));
                        
const SVGM: React.FC<SVGMProps> = ({ kind, className = '' }) => {
    const IconComponent = iconFiles[kind];
                          
    if (!IconComponent) return null;
    return (
        <Suspense fallback={<div>Loading...</div>}>
            <div className={className}>
                <IconComponent className={`fill-current ${className}`} alt={`${kind} icon`} />
            </div>
        </Suspense>
    );
};
                        
export default SVGM;

The scaffolded SVGM.tsx component accepts these property types:

  • kind
  • className

They are very straightforward, the kind prop tells your JSX which filename to look for in your SVGM directory, and the className prop is joined with currentColor to accept a text-color from TailwindCSS or a color from CSS, along with whatever other properties you want to set like margin or mx-auto.

Property kind

  • Use the kind prop to tell svgMagic which .svg file to load.

kind Dynamic Import prop Example Component Source:

SVGM.tsx
<div className="flex flex-wrap space-x-2 justify-center my-8">
    <SVGM kind="svgm-mark" className="h-8 w-8" />
    <SVGM kind="svgm-type" className="h-8 w-24" />
    <SVGM kind="tailwind" className="h-8 w-8" />
    <SVGM kind="react" className="h-8 w-8" />
    <SVGM kind="next" className="h-8 w-8" />
    <SVGM kind="svg-file" className="h-8" />
</div>

Property className

  • Use the className prop to tell svgMagic what className to apply to your SVG code, this can be used with Vanilla CSS or TailwindCSS.

For more information about Styling with the className prop, visit the Styling page.