react-fontawesome
react-fontawesome copied to clipboard
How can I check library already loaded certain icons?
Hey, everyone. I am building a component library using fontawesome, I have a main file like this.
//config fontawesome
import { library } from '@fortawesome/fontawesome-svg-core'
import { fas } from '@fortawesome/free-solid-svg-icons'
library.add(fas)
//export all the components
export { default as Button } from './components/Button'
export { default as Menu } from './components/Menu'`
...
So every time user import component, it will call library.add for one time.So my questions are,
#1 Call library.add() multiple times will add duplicate icons for many times? #2 If Question one is true, How can I check certain icon is already loaded and avoid to add them again?
Thanks so much.
@vikingmute if you are building a component library I highly recommend you use the explicit import method:
https://github.com/FortAwesome/react-fontawesome#explicit-import
Hey @robmadole , I am building a component library including all the free solid icons pack.(free-solid-svg-icons). Explicit importing will take lots of duplicate code and can be very annoying. Do we have a workaround for that?
@robmadole @vikingmute
I have the same problem, I am building a UI components library and my Icon component is built on top of the FontAwesomeIcon one.
My purpose is to use the Icon component as easily as the following:
<Icon name="hearth" />
but to do that I have to import all the involved libraries in my Icon component as the following:
import { fab } from '@fortawesome/free-brands-svg-icons';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
library.add(fas, fab);
this is quite annoying since every time I use library it will basically load ALL font-awesome (Icon component is a very basic one and is used in other components such as Button) and at the moment is the biggest dependency 😭😭😭
I think having a way to possibly load the icons when really needed would be perfect.
At the moment I came up with the following hook solution but it's quite gross and it just delays the loading of the whole library:
const useAsyncFontAwesomeLoader = () => {
const [isLoaded, setIsLoaded] = useState(fontAwesomeAlreadyLoaded);
useEffect(() => {
if (!fontAwesomeAlreadyLoaded) {
const loadLibs = () => import('@fortawesome/free-brands-svg-icons').then((fabLib) => {
library.add(fabLib.fab);
return import('@fortawesome/free-solid-svg-icons').then((fasLib) => {
library.add(fasLib.fas);
});
});
loadLibs().finally(() => {
setIsLoaded(true);
});
}
}, []);
return isLoaded;
};
then in my component:
const Icon = ({ name, color, size, className, ...rest }) => {
const isLoaded = useAsyncFontAwesomeLoader();
const classList = makeClasses(color, size, className);
return !isLoaded ? null : (<FontAwesomeIcon icon={name} className={classList} {...rest} />);
};
any better suggestion?