Home >Web Front-end >H5 Tutorial >Summary of various methods of using svg in react (with code)
This article introduces to you a summary of various methods of using svg in react (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Advantage
SVG can be read and modified by many tools (such as vscode)
No distortion, the image is clear when zoomed in or out
SVG files are pure XML and also a DOM structure
Easy to use, design software can directly export
Compatibility
Previous compatibility chart, or go to caniuse.com to view
How to use
Use directly in the template
const Home = () => ( <div> <svg> <rect></rect> </svg> </div> )
Convert svg to font
iconfont
Convert svg into react component
Conversion before project construction
Example:typescript-react-svg-icon-generator, we need a pre-command to convert svg.// svg-generator.js const generator = require('typescript-react-svg-icon-generator') const config = { svgDir: './svg/', destination: './Icon/index.tsx' } generator(config)
$ node ./svg-generator.jsUse:
import Icon from './Icon' export default class App extends Component { render() { return <icon></icon> } }In addition, svgr (mentioned below) also provides this solution, please check it yourself
Conversion when building the project
Example:@svgr/webpackYes. Yes, this is a webpack loader.// webpack rules config { test: /\.svg$/, loader: '@svgr/webpack' }
// 全局声明svg component定义 declare interface SvgrComponent extends React.StatelessComponent<react.svgattributes>> {} declare module '*.svg' { const content: SvgrComponent export default content }</react.svgattributes>
import IconReact from '@assets/svg/react.svg' const Home = () => ( <p> <iconreact></iconreact> </p> )The benefits of this solution are not only reflected in the conversion during build, but more importantly It fully inherits SVGAttributes and requires no additional learning costs! You can refer to the project ts-react-webpack4, or the scaffolding steamer-react-tsIn addition, there are react-svg, svg-react-loader, etc. It is also implemented in a similar way. Recommended related articles:
The role of svg path: How to use svg path in web development
How Storage Event implements inter-page communication
The above is the detailed content of Summary of various methods of using svg in react (with code). For more information, please follow other related articles on the PHP Chinese website!