Búsqueda de sitios web

javascript - Mejor manera de incluir SVG reutilizable en React


Estoy incluyendo SVG como un componente reutilizable en mi aplicación React. Un ejemplo del componente SVG es el siguiente

import React from 'react';

export default function IconComponent(): JSX.Element {
    const svg = `
    <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M36.4811 26.4927H29.7345C26.5728 26.4927 23.9995 23.921 23.9978 20.761C23.9978 17.5977 26.5711 15.0243 29.7345 15.0227H36.4811C37.1711 15.0227 37.7311 15.5827 37.7311 16.2727C37.7311 16.9627 37.1711 17.5227 36.4811 17.5227H29.7345C27.9495 17.5243 26.4978 18.976 26.4978 20.7593C26.4978 22.541 27.9511 23.9927 29.7345 23.9927H36.4811C37.1711 23.9927 37.7311 24.5527 37.7311 25.2427C37.7311 25.9327 37.1711 26.4927 36.4811 26.4927Z" fill="#0C1727"/>
</svg> `;

    return (
        <span
            className="icon icon-component"
            dangerouslySetInnerHTML={{ __html: svg }}
        />
    );
}


A nivel de página, estoy importando IconComponent y reutilizándolo. ¿Hay alguna otra mejor manera de incluir SVGs reutilizables en páginas de React que mejore el rendimiento/carga de la página?

Respuesta #1

Puedes crear un archivo estático sprites.svg en la carpeta pública y definir tu svg en la etiqueta symbol con un id específico

<svg
    display="none"
    width="0"
    height="0"
    version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
>
   <defs>
       <symbol id="your_icon_id">
           <path fill-rule="evenodd" clip-rule="evenodd" d="M36.4811 26.4927H29.7345C26.5728 26.4927 23.9995 23.921 23.9978 20.761C23.9978 17.5977 26.5711 15.0243 29.7345 15.0227H36.4811C37.1711 15.0227 37.7311 15.5827 37.7311 16.2727C37.7311 16.9627 37.1711 17.5227 36.4811 17.5227H29.7345C27.9495 17.5243 26.4978 18.976 26.4978 20.7593C26.4978 22.541 27.9511 23.9927 29.7345 23.9927H36.4811C37.1711 23.9927 37.7311 24.5527 37.7311 25.2427C37.7311 25.9327 37.1711 26.4927 36.4811 26.4927Z" fill="#0C1727"/>
       </symbol>
   </defs>
</svg>

y puedes usarlo llamando su id

const SvgIcon = ({ name, ...props }) => (
    <svg {...props}>
        <use xlinkHref={`/static/images/sprites.svg#${name}`} />
    </svg>
);

<SvgIcon name="your_icon_id" width={40} height={40}/>

De esta manera, el tamaño de tu paquete de JavaScript disminuirá porque no tiene código SVG

P/D: Puedes usar svgo para optimizar archivos de sprites SVG

Respuesta #2

1. SVG con webpack

línea de comandos

yarn add -D @svgr/webpack
webpack.config.js
const webpack = require('webpack');

module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      //...
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      },
    ],
  },
  //...
};

entonces

import Star from 'star_icon.svg';

<Star />

2. SVG como componente

import { ReactComponent as Star } from 'star_icon.svg';

<Star />
<Star width="64" height="64" fill="yellow" />

También puedes usar props así.

3. SVG como ruta

import Star from 'star_icon.svg';

<img src={Star} />

Espero que estos códigos te ayuden. Personalmente, recomiendo el segundo método.

Artículos relacionados