動態載入 Heroicons with React

動態載入 Heroicons with React

首先我們喜歡使用 Heroicons,我們常在我們的專案上使用它,我們也很喜愛這些 Icon,希望您也會喜歡。

我們希望可以透過資料來動態的產生出對應的 Icons

資料

    const Menus = [
        {
            id: 1,
            name: '客戶資料',
            icon: 'IdentificationIcon',
        },
        {
            id: 2,
            name: '物件',
            icon: 'HomeModernIcon',
        },
        {
            id: 3,
            name: '週計畫',
            icon: 'PuzzlePieceIcon',
        },

    ]

建立一個動態載入的函數

    import * as HIcons from "@heroicons/react/20/solid";
    
    const DynamicHeroIcon = (props) => {
        const { ...icons } = HIcons;
        const TheIcon = icons[props.icon];
        return (
            <>
                <TheIcon className={`h-6 w-6`} aria-hidden={true} />
            </>
        );
    };

使用


    <DynamicHeroIcon icon={item.icon} />
        

👍 大功告成

© 2023 YunBao 紜寶

Version 0.0.4