I have an array of emojis and each emoji has emoji
and label
field. I would like to know how to render emoji using map in my component.
I have stored all the emojis as SVG files in the src/assets/emojiIcons
.
Right now, I'm doing like this:
import { ReactComponent as Coin } from "../assets/emojiIcons/coin.svg"
import { ReactComponent as Rocket } from "../assets/emojiIcons/rocket.svg"
const DEFAULT_EMOJI_OPTIONS = [
{
emoji: Rocket,
label: "rocket",
},
{
emoji: Coin,
label: "coin",
},
]
export { DEFAULT_EMOJI_OPTIONS }
importing the emojis in my component like this:
import { DEFAULT_EMOJI_OPTIONS } from "../../utils/emojis"
const EmojiSection = () => {
return (
<div className="text-white border-2 border-gray-800 rounded p-3 my-8 max-w-xs mx-auto">
{DEFAULT_EMOJI_OPTIONS.map((emoji) => (
<emoji.emoji />
))}
</div>
)
}
Is there any better way of doing this?
CodePudding user response:
I believe the import { ReactComponent as Coin }
syntax only works if you're using create-react-app. If you are, then this is probably the best option, provided you don't need to re-colour the image or anything fancy like that.
If you're not using create-react-app, I'd just use an img
tag.
You can use file-loader
to import the svg, rather than needing to keep the path in a string.
In your webpack config (there are similar options for vite or other systems):
module.exports = {
module: {
rules: [
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: 'file-loader',
},
],
},
],
},
};
import Coin from "../assets/emojiIcons/coin.svg";
const DEFAULT_EMOJI_OPTIONS = [
{
emoji: Coin,
label: "coin",
},
.
.
.
];
.
.
.
const EmojiSection = () => {
return (
<div className="text-white border-2 border-gray-800 rounded p-3 my-8 max-w-xs mx-auto">
{DEFAULT_EMOJI_OPTIONS.map((emoji) => (
<img src={emoji.emoji} />
))}
</div>
);
};
CodePudding user response:
I don't have this two svg so i tried with string value. You can map in one component then you can actually render the component. You are using svg as component . While this svgs are images they don't have any export function. In react you easily map all the svgs with the help of tag.
import Coin from "../assets/emojiIcons/coin.svg"
import Rocket from "../assets/emojiIcons/rocket.svg"
const DEFAULT_EMOJI_OPTIONS = [
{
emoji: Rocket,
label: "rocket",
},
{
emoji: Coin,
label: "coin",
},
]
function Test() {
return (
<>
{DEFAULT_EMOJI_OPTIONS.map(({ emoji,label }) => (
<div >
<div>
<img src={emoji} alt="xyz" width={50}/>
<h2>{label}</h2>
</div>
</div>
))}
</>
)
}
export default Test;