Home  >  Article  >  Web Front-end  >  How to use svg elegantly in react

How to use svg elegantly in react

coldplay.xixi
coldplay.xixiOriginal
2020-12-17 10:00:114442browse

The elegant way to use svg in react: first install [svg-sprite-loader] and configure [/config/webpack.config.js]; then create a new icons folder under the src folder; Finally set up the SvgIcon component.

How to use svg elegantly in react

The operating environment of this tutorial: windows7 system, React17 version. This method is suitable for all brands of computers.

Related learning recommendations: react video tutorial

The elegant way to use svg in react:

1. Install svg-sprite-loader

yarn  add svg-sprite-loader --dev

or

npm i svg-sprite-loader -D

2. Configure/config/webpack.config.js (configuration after yarn eject)

Note: The newly added loader must be placed before the file-loader

Reason: The loader of webpack is executed from back to front

Added in loader Configure as follows

         {
              test: /\.(eot|woff2?|ttf|svg)$/,
              exclude: path.resolve(__dirname, "../src/icons"), //不处理指定svg的文件(所有使用的svg文件放到该文件夹下)
              use: [
                {
                  loader: "url-loader",
                  options: {
                    name: "[name]-[hash:5].min.[ext]",
                    limit: 5000, // fonts file size <= 5KB, use &#39;base64&#39;; else, output svg file
                    outputPath: "font",
                    publicPath: "font"
                  }
                }
              ]
            },
            {
              test: /\.svg$/,
              loader: "svg-sprite-loader",
              include: path.resolve(__dirname, "../src/icons"), //只处理指定svg的文件(所有使用的svg文件放到该文件夹下)
              options: {
                symbolId: "icon-[name]" //symbolId和use使用的名称对应      <use xlinkHref={"#icon-" + iconClass} />
              }
            },

3. Create a new icons folder under the src folder

Create a new svg folder under the icons folder and place the svg file

directory

How to use svg elegantly in react

index.js Load all svg files in the svg folder

const requireAll = requireContext => requireContext.keys().map(requireContext);
const svgs = require.context("./svg", false, /\.svg$/);
requireAll(svgs);

Then be sure to import src/icons in the react entry file src/index.js /index.js

The code is as follows

import "./icons";

4. SvgIcon component

Create a SvgIcon folder under the src/components folder and add index.jsx File

Directory

How to use svg elegantly in react

index.jsx component content is as follows:

import React from "react";
import PropTypes from "prop-types";
import styles from "./style.less"; //已启用 CSS Modules
const SvgIcon = props => {
  const { iconClass, fill } = props;
  return (
    <i aria-hidden="true" className="anticon">
      <svg className={styles["svg-class"]}>
        <use xlinkHref={"#icon-" + iconClass} fill={fill} />
      </svg>
    </i>
  );
};
SvgIcon.propTypes = {
  // svg名字
  iconClass: PropTypes.string.isRequired,
  // 填充颜色
  fill: PropTypes.string
};
SvgIcon.defaultProps = {
  fill: "currentColor"
};
export default SvgIcon;

style.less

.svg-class {
  display: inline-block;
  overflow: hidden;
  font-size: 14px;
  min-width: 14px;
  width: 1em;
  height: 1em;
}

5. Use

to put the svg file you want to use in the src/icons/svg directory. When using it, just give the svg name to iconClass

import React from "react";
import SvgIcon from "@/components/SvgIcon";
const Demo = () => {
    const svgName="content"  // content.svg  已经放到 /src/icons/svg/  目录下
  return <SvgIcon iconClass={svgName} />;
};
export default Demo;

Related learning recommendations: javascript video tutorial

##

The above is the detailed content of How to use svg elegantly in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn