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
##Compatibility is not a big problem. Of course, if your website still needs to be compatible with these old browsers, there are corresponding solutions in the community, such as some of Zhang Xinxu's SVG downward compatibility graceful downgrade technology
How to use
Use directly in the template
const Home = () => ( <div> <svg> <rect></rect> </svg> </div> )
Convert svg to font
iconfont
Copy the code directly into the project css, customize your label style, and refer to Alibaba’s official article. It is simple and crude to use, and has high browser compatibility. However, it needs to be uploaded manually (other solutions are welcome to add) , In addition, if you want to deploy to an environment other than Alibaba's CDN, you need to download it first and then upload it to the target environment. It is a bit troublesome.In addition, icomoon and others provide similar solutions
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.js
import Icon from './Icon' export default class App extends Component { render() { return <icon></icon> } }
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 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!