reactjssvg-react-loader

Issue with usage of SVG as a ReactComponent


I am trying to write a mapper that will return a SVG as a React component.

Here is how I import the SVG:

import {ReactComponent as Games} from './assets/game.svg';

And here is how I return the SVG:

return <Games/>;

Somehow one of my jest test as follows:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `CategoryChip`.

Here is the component that uses the mapper:

const CategoryChip: React.FC<ICategoryChip> = ({ label }) => {

  if (label.toUpperCase().includes('all'.toUpperCase())) {
    return <span className="category-chip-all">{label}</span>;
  }

  return (
    <span className="category-chip">
      {mapCategory(label)}<span className="category-text">{label}</span>
    </span>
  );
}

export default CategoryChip;

Here is the complete file for the mapper:

import * as React from 'react';
import {ReactComponent as Development} from './assets/development.svg';
import {ReactComponent as Education} from './assets/education.svg';
import {ReactComponent as Games} from './assets/game.svg';
import {ReactComponent as Identity} from './assets/identity.svg';
import {ReactComponent as Marketplace} from './assets/market-place.svg';
import {ReactComponent as NFT} from './assets/nft.svg';
import {ReactComponent as Other} from './assets/other.svg';
import {ReactComponent as Security} from './assets/security.svg';
import {ReactComponent as Social} from './assets/social.svg';
import {ReactComponent as Defi} from './assets/defi.svg';

export const mapCategory: React.FC<any> = (category: string) => {
  const _category = category.toUpperCase();

  switch (_category) {
    case 'DEFI':
      return <Defi/>;
    case 'DEVELOPMENT':
      return <Development/>;
    case 'EDUCATION':
      return <Education/>;
    case 'GAMES':
      return <Games/>;
    case 'IDENTITY':
      return <Identity/>;
    case 'MARKETPLACE':
      return <Marketplace/>;
    case 'NFT':
      return <NFT/>;
    case 'OTHER':
      return <Other/>;
    case 'SECURITY':
      return <Security/>;
    case 'SOCIAL':
      return <Social/>;
  }
}

Can someone please tell me what could be wrong with my code? The error message seems to indicate there is an error with my usage of imports. Also the error occurs only in the tests and not when I run the app.


Solution

  • It was indeed an issue with jest not finding SVG images.

    Here is how I sorted the problem:

    In jest config:

      moduleNameMapper: {
        '\\.svg$': '<rootDir>/test/__mocks__/svgrMock.js',
        ...
    

    svgrMock.js:

     module.exports = { ReactComponent: 'IconMock' }
    

    See also: