Reputation: 865
I have only been programming with react for a short time and I don't know if there is a more efficient way to perform this task. I have a series of files that correspond to some svg files. An example would be the following.
export default function CheckIcon(props) {
return (
<Icon {...props}>
options={ CheckIcon }
/>
);
}
CheckIcon.displayName = 'CheckIcon';
then I import them into a component that I call Icon.js where I make a switch for each of the cases and return the corresponding component.
import React from 'react';
import CloseIcon from './icons/CloseIcon';
import CheckIcon from './icons/CheckIcon';
import SumIcon from './icons/SumIcon';
import SubtractIcon from './icons/SubtractIcon';
import MultiplyIcon from './icons/MultiplyIcon';
import DivideIcon from './icons/DivideIcon';
export default function Icon({ type, ...props }) {
const getIcon = () => {
switch (type) {
case 'close':
return <CloseIcon {...props} />;
case 'check':
return <CheckIcon {...props} />;
case 'sum':
return <SumIcon {...props} />;
case 'subtract':
return <SubtractIcon {...props} />;
case 'multiply':
return <MultiplyIcon {...props} />;
case 'divide':
return <DivideIcon {...props} />;
default:
break;
}
};
return getIcon();
}
and finally I import the Icon.js file into the component where I am going to display my html
<div>
{() => {
return (
<Icon type="close" />
<Icon type="check" />
<Icon type="sum" />
<Icon type="subtract" />
<Icon type="multiply" />
<Icon type="divide" />
);
}}
</div>
My question is, is there a more efficient way to dynamically import into my Icon.js component the different components that correspond to each of the seg?
thank you all for your time and help in advance.
Upvotes: 6
Views: 11514
Reputation: 11382
You can do this with Dynamic Imports.
But the real answer is that you're probably using a bundler for your code, and how to do Dynamic Imports will depend on what bundler you are using. Some bundlers have different syntax. Webpack will recognise import()
.
But the real real answer is that if you're using a bundler, don't try to dynamically import code. It's an early optimization that will cause you more problems than it is worth. Let the bundler do its thing. Webpack does code splitting and tree shaking and as your code base gets larger, it will be easier to just let Webpack apply the optimizations.
See also the Dynamic Imports and Lazy Loading sections of the Webpack documentation (if you're using Webpack).
Upvotes: 3
Reputation: 17504
I think you could alternatively do it by using type
as the icon name the use require
to dynamically load your icon as following:
// Icon.js
import React from 'react';
export default function Icon({ type, ...props }) {
const TheIcon = require(`./icons/${type}`).default;
return <TheIcon {...props} />
}
// Then use it
import Icon from './Icon';
<Icon type="CloseIcon" />
Upvotes: 5