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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With