Search code examples
ionic-frameworksvgionic5ionic-react

Ionic 5 / React: Use ion-icon to embed custom SVG


I have a React app in Ionic 5 and I want to add some custom SVGs to it.

This SO question is about Angular, but my question is about React.

My app folder structure looks like this:

  • src
    • assets
      • listen.svg
      • SvgListen.tsx

Here is SvgListen.tsx:

import React from 'react';
import { ReactComponent as ListenSvg } from './listen.svg';
import { IonIcon } from '@ionic/react';

const SvgListen = () => (
  <>
    <ListenSvg />
    <IonIcon src="./listen.svg" font-size="48px" />

  </>
);

export default SvgListen;

When testing the app in Chrome, I get this HTML:

<ion-icon src="./listen.svg" font-size="48px" role="img" class="ios hydrated"></ion-icon>

The <ListenSvg /> that I imported is displayed correctly; however, the ion-icon is not displayed. There is no error message, either.

I checked this blog post, but no luck with the approach outlined there, either.

How can I show a custom SVG using <IonIcon> in Ionic 5?


Solution

  • According do the Create React App docs you can import images to get their final path in the output bundle:

    import React from 'react';
    import { IonIcon } from '@ionic/react';
    import listenSvg from './listen.svg';
    
    const SvgListen = () => (
      <IonIcon src={listenSvg} font-size="48px" />
    );
    
    export default SvgListen;