Home Web Front-end JS Tutorial How to use SVG in React and Vue projects

How to use SVG in React and Vue projects

Jun 06, 2018 pm 03:24 PM
react

This article mainly introduces the method of using SVG in React and Vue projects. Now I will share it with you and give you a reference.

In some modern flat design websites, especially mobile websites, they often contain many simple and clear small icons, such as website icons, user default avatars, and fixed switching bars at the bottom of the mobile home page. Etc., these small icons are usually made by artists, and may be placed on sprites, and then cropped and displayed on the front end.

In fact, there is no need for artists to do these simple small icons. The front end can use svg code to draw these simple icons, and, because These icons are described with codes, so if you want to modify these icons, such as changing the icon color, icon shape, size, etc., it is just a matter of changing a few lines of code. It is very simple and there is no need to rework the artist at all.

This article does not explain how to use svg to draw pictures. If you don’t know svg, you can go here to check it out. This article mainly talks about how to use svg in the website.

Use of SVG in general web pages

SVG uses XML format to define images. You can also think of it as a general HTML tag, which is embedded in the web page and presented. To produce a certain effect, the basic example of using svg in a web page is as follows:

<body>
  <svg width="100" height="100" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <rect width="100%" height="100%" style="fill:pink;stroke-width:1;stroke:rgb(0,0,0)"/>
  </svg></body>
Copy after login

The effect is as follows:

As you can see, using svg in an ordinary web page is It's very simple, as long as you can draw the svg icon, rendering it on the web page is not a problem at all.

Using Svg in Vue

You can use svg in Vue just like you use svg in ordinary web pages. However, since you have chosen vue for component development project, so a long section of svg interspersed among a bunch of components is a bit unsightly.

One solution is to use the use tag of svg. Instead of writing the code to draw the svg icon directly in the main page, put this large section of code into another file, and then use use Just quote this code for drawing icons (it seems that this is how Ele.me mobile terminal does it).

For example, put all the code for drawing svg into the svg-icon.vue file. Use symbol tags to separate the drawing codes for all icons and name them separately to avoid confusion. Then treat this file as a component. Export, introduce this component into the main page, and then introduce it through the use tag where the svg icon needs to be used.

svg-draw.vue code example is as follows:

<template>
 <svg
  xmlns="http://www.w3.org/2000/svg"
  xmlnsXlink="http://www.w3.org/1999/xlink"
  style={{position:&#39;absolute&#39;,width:0,height:0}}>
  <defs>
   <symbol viewBox="0 0 26 31" id="location">
    <path xmlns="http://www.w3.org/2000/svg" d="M512.571517 65.907059c-204.736964 0-370.715183 165.979242-370.715183 370.724393 0 94.440929 35.320437 180.625824 93.462648 246.083651 1.572822 2.690272 3.50994 5.225001 5.817496 7.531534l240.297878 251.597225c1.279133 1.864464 2.736321 3.64297 4.393054 5.298679 2.111081 2.111081 4.418636 3.90596 6.856152 5.402033 14.458293 10.06524 34.491559 8.658194 47.393403-4.242627 3.26537-3.263323 5.78782-6.987135 7.582699-10.960633L783.610536 690.24766c1.867534-1.866511 3.489474-3.88447 4.876054-6.010901 58.951647-65.640999 94.819552-152.431691 94.819552-247.604284C883.305119 231.886301 717.325877 65.907059 512.571517 65.907059zM512.390391 588.611865c-82.734306 0-149.814074-67.087954-149.814074-149.842727 0-82.753749 67.079768-149.833517 149.814074-149.833517 82.772168 0 149.851936 67.079768 149.851936 149.833517C662.242328 521.523911 595.161536 588.611865 512.390391 588.611865z" fill="#d81e06"/>
   </symbol>
  </defs>
 </svg></template>
Copy after login

The entire vue component exports a large svg. This svg contains many small icons, similar to sprites. Each icon uses symbols and name them separately for easy reference.

Usage examples are as follows:

// index.vue
...<svg class="location-icon">
 <use xlink:href="#location" rel="external nofollow" ></use></svg>...
Copy after login

Then, you can see that the corresponding svg icon appears successfully on the web page:

However, There is another problem. If the current website needs to use a lot of svg icons, the file size of svg-icon.vue will inevitably become larger. The current web page name only needs to use one of the svg icons. As a result, you will have hundreds of icons. The svg code is all loaded in, which is obviously not very friendly. It is best to load it on demand. Just load the icons that the current web page needs. Even some icons that may or may not appear will be loaded when they should appear. If If no chance arises, it never loads.

There are many such plug-ins on Github. I will introduce a plug-in that I think is very useful: vue-svg-icon, which is easy to use and quick to get started.

First of all, install this plug-in, not much to say. After the installation is completed, register this plug-in in the entry file of the project to facilitate global calls:

import Icon from &#39;vue-svg-icon/Icon.vue&#39;Vue.component(&#39;icon&#39;, Icon)
Copy after login

Then in the root directory /src Create a new svg directory under the directory (currently this path can only be like this and cannot be configured as other paths and directories), and then put the svg file of the svg icon you want to use in this directory.

For example, the svg of a WeChat icon is as follows:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg t="1502683891821" class="icon" style="" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2885" xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16">
<defs>
<style type="text/css"></style>
</defs>
<path d="M282.6 363.8c-23.7 0-47-15.7-47-38.9 0-23.7 23.3-38.9 46.5-38.9 23.7 0 38.9 15.2 38.9 38.9 0.5 23.2-15.1 38.9-38.4 38.9zM500.4 286c23.7 0 38.9 15.2 38.9 38.9 0 23.3-15.2 38.9-38.9 38.9-23.3 0-47-15.7-47-38.9 0-23.7 23.7-38.9 47-38.9z m167.7 84.5c9.8 0 19.7 0.5 30 1.8-27.3-125.6-161.4-218.7-314.4-218.7C212.4 153.6 72 270.3 72 418.3c0 85.9 46.5 155.6 124.8 210.2l-31.3 93.9 109.1-54.6c38.9 7.6 70.2 15.7 109.1 15.7 9.4 0 19.2-0.5 29.1-1.3-6.3-20.6-9.8-42.9-9.8-65.3-0.1-136 116.6-246.4 265.1-246.4z" p-id="2886"></path><path d="M772.7 573.9c-15.2 0-30.9-15.2-30.9-30.9 0.5-15.7 15.7-31.3 30.9-31.3 23.7 0 39.4 15.7 39.4 31.3-0.1 15.7-15.7 30.9-39.4 30.9z m-171.3 0c-15.2 0-30.9-15.2-30.9-30.9s15.7-31.3 30.9-31.3c23.7 0 38.9 15.7 38.9 31.3 0.5 15.7-15.2 30.9-38.9 30.9zM952 613.3C952 488.5 827.2 387 687.3 387c-148 0-264.7 101.5-264.7 226.3 0 124.8 116.7 225.8 264.7 225.8 31.3 0 62.6-8.1 93.5-15.7l85.9 47-23.7-77.8c62.5-47 109-109.1 109-179.3z" p-id="2887">
</path>
</svg>
Copy after login

Save the above code into a .svg file, such as wx.svg, and put it in the /src/svg directory, and you are done preparation work.

Next, if you want to use it, it is very simple. Just write this directly in the vue component:

<template>
  <icon class="wx-icon" name="wx"></icon></template>
Copy after login

When refreshing the page, open the console and you can see The wx.svg file is loaded into the page. In this way, the on-demand introduction of the svg file is realized.

Using Svg in React

Using Svg in React is the same as vue. There are also three solutions. One is to write directly in the reader method of react. svg code, the second is to put all the svg drawing code into a file, and then load the file at once, using the use tag to reference the corresponding svg pattern, and the third is to use a plug-in to introduce it on demand.

第一种直接在 渲染方法中写入 svg的方法就不多说了,第二种也很简单 ,和 vue一样,只不过写法上需要注意一下。

render() {
  return (
   <svg
    xmlns="http://www.w3.org/2000/svg"
    xmlnsXlink="http://www.w3.org/1999/xlink"
    style={{position:&#39;absolute&#39;,width:0,height:0}}>
    <defs>
     <symbol viewBox="0 0 26 31" id="location">
      <path fill="#FFF" fillRule="evenodd" d="M22.116 22.601c-2.329 2.804-7.669 7.827-7.669 7.827-.799.762-2.094.763-2.897-.008 0 0-5.26-4.97-7.643-7.796C1.524 19.8 0 16.89 0 13.194 0 5.908 5.82 0 13 0s13 5.907 13 13.195c0 3.682-1.554 6.602-3.884 9.406zM18 13a5 5 0 1 0-10 0 5 5 0 0 0 10 0z"></path>
     </symbol>
     <symbol viewBox="0 0 14 8" id="arrow">
      <path fill="#FFF" fillRule="evenodd" d="M5.588 6.588c.78.78 2.04.784 2.824 0l5.176-5.176c.78-.78.517-1.412-.582-1.412H.994C-.107 0-.372.628.412 1.412l5.176 5.176z"></path>
     </symbol>
    </svg>
   )
}
Copy after login

主要是需要注意,因为 react使用 jsx语法,不允许出现 - 连字符,所以像 fill-rule这样的属性,就必须写成 fillRule,引用的时候同样如此。

// 引用的时候需要将 `xlink:href` 改写成 xlinkHref<svg className="arrow-left">
  <use xlinkhref="#arrow-left" rel="external nofollow" ></use>
 </svg>
Copy after login

第三种按需引入,只加载当前需要的 svg形状,同样是将每一个 svg图片作为一个单独的文件保存,然后再需要使用的地方进行引用。 Github上有个项目 react-svg,这个项目内部其实是对 SVGInjector的包装,

安装 react-svg之后,就可以像下面这样使用了:

import ReactSVG from &#39;react-svg&#39;

ReactDOM.render(
 <ReactSVG
  path="atomic.svg"
  callback={svg => console.log(svg)}
  className="example"
 />,
 document.querySelector(&#39;.Root&#39;)
)
Copy after login

一般都只是在使用小图标的时候才考虑 svg,而这些小图标一般都比较简约,绘制起来也没什么难度,不过大部分情况下没有必要自己来画,很多网站都提供svg的图标下载,例如阿里的 iconfont,图标数量众多,基本可以满足绝大部分的需求,另外,类似的网站还有 easyicon 、 icomoon等。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

有关在Vue中使用Compass的具体方法?

如何关闭Vue计算属性自带的缓存功能,具体步骤有哪些?

如何解决vue 更改计算属性后select选中值不更改的问题,具体操作如下

The above is the detailed content of How to use SVG in React and Vue projects. 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 build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to package and deploy front-end applications using React and Docker How to package and deploy front-end applications using React and Docker Sep 26, 2023 pm 03:14 PM

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install

How to build real-time data processing applications using React and Apache Kafka How to build real-time data processing applications using React and Apache Kafka Sep 27, 2023 pm 02:25 PM

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

See all articles