Fill for external SVG file in React

11,682

Solution 1

If you use Create React App, then the easiest solution is to import SVG as a React component

import { ReactComponent as User } from './icons/user.svg';

const View = () => <User />;

See more in the docs: https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files#adding-svgs

Solution 2

Include an external SVG image with four lines of code:

<svg>
  <use xlinkHref={'/images/logo.svg#Version-2'}>
  </use>
</svg>

In this case the SVG image "logo.svg" will have an ID in it named: "Version-2". The part after the hash "#" maps to an ID in the SVG image that must of course exist.

Share:
11,682

Related videos on Youtube

Telion
Author by

Telion

Updated on June 04, 2022

Comments

  • Telion
    Telion almost 2 years

    It doesn't seem to be possible so far to control the SVG elements that are stored in a separate file. I thought maybe with WebPack and npm modules it should be possible yet can't find a simple or convenient solution. Is it possible to import element like this?

    import icon from "./icons/user.svg"
    
    <icon fill="red" />
    

    I don't understand why it is so hard to work with SVG here, or why can't I find enough information on the topic. Maybe I am doing this wrong? Are there better ways to manage a lot of icons for a React website? I need will be using quite a few, like social networks stuff and similar.

    • Sulthan
      Sulthan about 6 years
      You can simply output svg as html.
    • Telion
      Telion about 6 years
      @Sulthan can I change the colors that way?
    • Sulthan
      Sulthan about 6 years
      You can always use styles to change colors.
    • Telion
      Telion about 6 years
      @Sulthan Please give an example of the code. I have a lot of SVG icons and simply adding them to the App code might make a lot of useless code. I want it to stay clear but flexible.
    • Sulthan
      Sulthan about 6 years