reactjscreate-react-appfluent-uifluentui-reactoffice-ui-fabric-react

How to register custom icons by reading a SVG file from path?


I am building an application making use of @fluentui/react (version 8.34.7) and I am using create-react-app.

One of the things I would like to do is register custom icons which are in SVG format. Following the example here, I came up with the following code:

registerIcons({
    icons: {
        'hamburger-icon': (
            <svg viewBox="0 0 16 16" role="presentation" focusable="false" aria-hidden="true">
                <g>
                    <path d="M1 4.5v-1h14v1zm0 4v-1h14v1zm0 4v-1h14v1z"></path>
                </g>
            </svg>                
        )
    }
});

and this works perfectly fine. I can reference hamburger-icon in my code and get the icon to display.

However, the issue with the code above is that I have to include svg file contents in my code. What I would like to do is read the SVG file contents and then use it in registerIcons method. I am not sure how I can do that.

If I do something like:

import Hamburger from 'assets/images/hamburger.svg';

I get a URL.

If I do something like:

import {ReactComponent as HamburgerIcon} from 'assets/images/hamburger.svg';

I get a React component whereas registerIcon method expects a React element.

Is it possible to simply specify a file path of an SVG file and register icon from that?


Solution

  • Well, it was ridiculously simple! All I had to do was this:

    import {ReactComponent as HamburgerIcon} from 'assets/images/hamburger.svg';
    
    registerIcons({
        icons: {
            'hamburger-icon': React.createElement(HamburgerIcon)
        }
    });
    

    and all worked well.