Home > Software engineering >  I want to add SVG icons to my iconsData.js and then render them on iconList.jsx
I want to add SVG icons to my iconsData.js and then render them on iconList.jsx

Time:01-06

I was trying to add path of the SVG icons in iconsData.jsx but while rendering it is considered as string and rendering the path itself.

iconsData.jsx

export const Data = [
  { key: "01", iconName: "tumblr" },
  { key: "02", iconName: "twitch" },
  { key: "03", iconName: "twitter" },
];

iconList.jsx

import React from "react";
import "./IconsList.scss";
import { Data } from "../../Data/iconsData";
import { Link } from "react-router-dom";

function iconsList() {
  return (
    <div id="x__iconsFeild">
      <ul id="x__iconsList" className="d-flex align-items-start flex-wrap p-0">
        {Data.map(({ key, iconName }) => (
          <li key={key} className="list-unstyled">
            <Link
              to={`/icons/${key}`}
              className="iconWrapper p-2 small align-items-center justify-content-center border rounded shadow"
            >
              {iconName}
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default iconsList;

I want to render the icon inside the Link tag.

enter image description here

can anyone please help me with this.

CodePudding user response:

you need to import SVG first by any name and then pass it to the object

import svgImage1 from "../../path";
import svgImage2 from "../../path";
import svgImage3 from "../../path";

export const Data = [
  { key: "01", iconName: svgImage1 },
  { key: "02", iconName: svgImage2 },
  { key: "03", iconName: svgImage3 },
];

CodePudding user response:

Assuming this project is setup using create-react-app, as there is no webpack.config file in file list.

create an index file in Icons folder as below:

import { ReactComponent as TumblrIcon} from './tumblr.svg';
import { ReactComponent as TwitchIcon} from './twitch.svg';
import { ReactComponent as TwitterIcon} from './twitter.svg';

export const IconIndex = {
  tumblr: <TumblrIcon />,
  twitch: <TwitchIcon />,
  twitter: <TwitterIcon />
}

and then in iconList.jsx:

import { IconIndex } from "<path>/Icons";
...
...
       <Link
          to={`/icons/${key}`}
          className="iconWrapper p-2 small align-items-center justify-content-center border rounded shadow"
        >
          {IconIndex[iconName]}
        </Link>

The variable within {} must be a JSX element.

Take care you are including only the icons that are actually used in Icons/index.tsx, else final bundle will have unnecessary, svg code and bundle will be bigger.

  • Related