Home Web Front-end H5 Tutorial Summary of various methods of using svg in react (with code)

Summary of various methods of using svg in react (with code)

Aug 02, 2018 pm 02:39 PM
react.js svg typescript Front-end engineering

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

Summary of various methods of using svg in react (with code)

  • 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

Summary of various methods of using svg in react (with code)

##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

There are various options, the one that suits your needs is the best

Use directly in the template

const Home = () => (
    <div>
        <svg>
            <rect></rect>
        </svg>
    </div>
)
Copy after login
  1. If each svg needs to be drawn by the front end, the requirements for the front end are higher.

  2. If each icon is copied from the svg code given by the designer, various labels must be changed, and an error will be reported if the error is corrected

This method is not friendly

Convert svg to font

iconfont

Summary of various methods of using svg in react (with code)

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

Please note: The following will include typescript related configuration

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)
Copy after login
$ node ./svg-generator.js
Copy after login
Use:

import Icon from './Icon'
export default class App extends Component {
    render() {
        return <icon></icon>
    }
}
Copy after login
In addition, svgr (mentioned below) also provides this solution, please check it yourself

Conversion when building the project

Example:

@svgr/webpack

Yes. Yes, this is a webpack loader.

// webpack rules config
{
    test: /\.svg$/,
    loader: '@svgr/webpack'
}
Copy after login
// 全局声明svg component定义
declare interface SvgrComponent extends React.StatelessComponent<react.svgattributes>> {}

declare module '*.svg' {
    const content: SvgrComponent
    export default content
}</react.svgattributes>
Copy after login
import IconReact from '@assets/svg/react.svg'

const Home = () => (
    <p>
        <iconreact></iconreact>
    </p>
)
Copy after login
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-ts

In 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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to call the method of child component in React parent component How to call the method of child component in React parent component Dec 27, 2022 pm 07:01 PM

Calling method: 1. Calls in class components can be implemented by using React.createRef(), functional declaration of ref or props custom onRef attribute; 2. Calls in function components and Hook components can be implemented by using useImperativeHandle or forwardRef to throw a child Component ref is implemented.

5 common JavaScript memory errors 5 common JavaScript memory errors Aug 25, 2022 am 10:27 AM

JavaScript does not provide any memory management operations. Instead, memory is managed by the JavaScript VM through a memory reclamation process called garbage collection.

Let's talk about how to use SVG to achieve image mosaic effect Let's talk about how to use SVG to achieve image mosaic effect Sep 01, 2022 am 11:05 AM

How to use SVG to achieve image mosaic effect without using Javascript? The following article will give you a detailed understanding, I hope it will be helpful to you!

How does Vue3+TypeScript+Vite use require to dynamically introduce static resources such as images? How does Vue3+TypeScript+Vite use require to dynamically introduce static resources such as images? May 16, 2023 pm 08:40 PM

Question: How to use require to dynamically introduce static resources such as images in a Vue3+TypeScript+Vite project! Description: When developing a project today (the project framework is Vue3+TypeScript+Vite), it is necessary to dynamically introduce static resources, that is, the src attribute value of the img tag is dynamically obtained. According to the past practice, it can be directly introduced by require. The following code: Write After uploading the code, a wavy line error is reported, and the error message is: the name "require" cannot be found. Need to install type definitions for node? Try npmi --save-dev@types/node. ts(2580) after running npmi--save-d

How to develop high-performance computing functions using Redis and TypeScript How to develop high-performance computing functions using Redis and TypeScript Sep 20, 2023 am 11:21 AM

Overview of how to use Redis and TypeScript to develop high-performance computing functions: Redis is an open source in-memory data structure storage system with high performance and scalability. TypeScript is a superset of JavaScript that provides a type system and better development tool support. Combining Redis and TypeScript, we can develop efficient computing functions to process large data sets and make full use of Redis's memory storage and computing capabilities. This article will show you how to

How to use TypeScript in Vue3 How to use TypeScript in Vue3 May 13, 2023 pm 11:46 PM

How to declare a type with field name enum? By design, the type field should be an enumeration value and should not be set arbitrarily by the caller. The following is the enumeration declaration of Type, with a total of 6 fields. enumType{primary="primary",success="success",warning="warning",warn="warn",//warningaliasdanger="danger",info="info",}TypeSc

How to convert svg to jpg format How to convert svg to jpg format Nov 24, 2023 am 09:50 AM

svg can be converted to jpg format by using image processing software, using online conversion tools, and using the Python image processing library. Detailed introduction: 1. Image processing software includes Adobe Illustrator, Inkscape and GIMP; 2. Online conversion tools include CloudConvert, Zamzar, Online Convert, etc.; 3. Python image processing library, etc.

How to implement data type conversion function in TypeScript using MySQL How to implement data type conversion function in TypeScript using MySQL Jul 29, 2023 pm 02:17 PM

How to implement data type conversion function in TypeScript using MySQL Introduction: Data type conversion is a very common requirement when developing web applications. When processing data stored in a database, especially when using MySQL as the back-end database, we often need to convert the data in the query results to the type we require. This article will introduce how to use MySQL to implement data type conversion in TypeScript and provide code examples. 1. Preparation: Starting

See all articles