3

I have some icons that lays in svg file that i need to use in my React application the problem is that all it says when i try to import it is "Cannot find module".

the class looks like this

import * as React from "react";
import "./LeaderboardBar.scss";
import Trophy from './icon_tournament.svg'

export interface Props
{
    display: boolean
}

export interface State
{

}

export class LeaderboardBar extends React.Component<Props, State>
{
    render()
    {
        return (
            <div id="leaderboard-bar">
            <div>
                <p id="leaderboard-bar-text">Raging Rex Tournament</p>
            </div>
            <div id="rank-text">
                <p id="leaderboard-bar-text">Your Rank  <span id="gold-text">77/542</span></p>
            </div>
            <div id="score-text">
                <p id="leaderboard-bar-text">Score <span id="gold-text">54</span></p>
            </div>
            <div id="terms-text">
                <p id="leaderboard-bar-text">Terms & Info</p>
            </div>
            </div>
        )
    }
}

i have https://www.npmjs.com/package/@svgr/webpack installed but the problems stays the same. What is the best practice in importing svg into React?

Johan Jönsson
  • 539
  • 1
  • 10
  • 23

2 Answers2

2

To answer your question regarding what is the best practice in importing SVG into react, here is a really good way:

import { ReactComponent as SvgSmiley } from "./assets/smiley.svg";

function App() {
  return (
    <div className="App">
      <SvgSmiley style={{ fill: "green" }} />
    </div>
  );
}

Where the SVG file just contains SVG markup. It's located in the same directory as the code above, but under another folder called 'assets'.

This way allows you to control the SVG styling, like fill from your code.

See this working here.

Read more on how to get fancy with SVG icons.

bot19
  • 664
  • 8
  • 18
  • 1
    @PsychoX did you get a chance to look at the working example? There's probably something in your SVG that is overriding the colour. Check via element inspector if your set colour is coming through and if so, if it's getting over written by another style. – bot19 Feb 26 '20 at 02:16
0

Try using url-loader and file-loader on your webpack config, with this configuration:

{ test: /\.(jpg|png|svg)$/, loader: 'url-loader', options: { limit: 25000, }, }, { test: /\.(jpg|png|svg)$/, loader: 'file-loader', options: { name: '[path][name].[hash].[ext]', }, },

rubentd
  • 1,245
  • 11
  • 25