简体   繁体   中英

Import SVG icons from another folder

I want to import svg icons from my icon folder, to change the color of the icons I have to give fill parameter to path inside SVG. So i need import and to show only SVG but not like <img src="icon.svg"/> .

I first put one SVG right inside the component and it shows no problem. but I have a lot of icons I can't put everything inside the component.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";

export const Gunicon = ({ name, height, width, color, bold }) => {
  const classes = makeStyles(theme => {
    /* i want to give style like this */
    return {
      gunicon: {
        "& svg": {
          height,
          width,
          "& path": {
            fill: color,
            stroke: color,
            strokeWidth: bold
          }
        }
      }
    };
  });

  /* this is working. but i dont like this */
  const ico = (
    <svg height={height} width={width} viewBox="0 0 512 512">
      <path d="test svg" fill={color} stroke={color} strokeWidth={bold} />
    </svg>
  );

  return (
    <div className={classes.gunicon}>
      {/* dont working */}
      {require(`./icons/${name}.svg`)}
      {/* working */}
      {ico}
    </div>
  );
};

when i am writing as {require("./icons/${name}.svg")} . this is showing me only path to SVG. But i want import every SVG by name and only SVG

Ok, my friend.

I guess you are using create-react-app and you don't need to configure your webpack (I hope nowadays no one knows what is webpack)

So, what did they in create-react-app is added loader for svg for you, and map source of the loaded asset to the field ReactComponent . What you need to do is:

  const { ReactComponent: Icon } = require(`./icons/${name}.svg`);
  return (
    <Icon />
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM