Use images of React: Use of componentization in SVG is referenced by symbol

The effect

Codepen: SVG – in – the react

ICONS can be quickly selected by name.

The principle of

The symbol referenced


This is a completely new way of using it, and it’s the mainstream of the future, and the recommended use of the platform right now. This usage is actually a collection of SVG, which has the following characteristics compared to the two above:

  • Multi-color ICONS are no longer limited by monochrome.
  • With a few tricks, support, like fonts, passesfont-size.colorTo adjust the style.
  • Poor compatibility, support ie9+, and modern browsers.
  • Browser rendering of SVG is mediocre, not as good as PNG.

In a normal project, SVG is usually introduced through webPack.

import iconXXX from 'xxx.svg';
Copy the code

But this is trivial and hard to type, error prone.

Through the website iconfont alibaba vector icon library, generate THE JS containing THE SVG collection and mount it to the body, and then you can select the ICONS one by one through the USE attribute of SVG. For general use, you can refer to the iconfont- Alibaba vector icon library help center, where react has carried out componentization encapsulation and type completion.

implementation

Packaging components

IconBase.tsx

import React from "react";

export type IconName = "like"|"star"|"share";

/** The underlying component of the icon's symbol reference */
export const IconBase = ({ name, ... p }: { name: IconName; } & JSX.IntrinsicElements["svg"]) = > {
  return (
    <svg className="icon-box" aria-hidden="true" {. p} >
      <use xlinkHref={"#icon-"+name} ></use>
    </svg>
  );
};
Copy the code

Explanation:

  • IconName: specifies the name of all imported ICONS
  • P: Passthrough some of the original SVG property Settings

Adding the global CSS

 .icon-box{
    width: 1em;
    height: 1em;
    / * vertical - align: 0.15 em. * /
    fill: currentColor;
    overflow: hidden;
    display: block;
  }
Copy the code

use

<IconBase name="like"></IconBase>
Copy the code

Explanation:

  • Name: Select the icon type

conclusion

The introduction of ICONS is also very useful through the introduction of SVG collections and componentized encapsulation. If this post helped you, feel free to like it and let more people see it.

Reference

  1. Iconfont – Alibaba vector icon library
  2. Iconfont – Alibaba vector icon library help center