Home > Enterprise >  SVG files Import in React
SVG files Import in React

Time:12-31

I'm building a component in React Typescript and when I try to import svg files, the app doesn't render them.

I've tried all kinds of imports these below:

import { ReactComponent as /*any name*/} from '../../assets/';
const Name = require('../../assets');
import Name from '../../assets/';

also tried the custom-ds thing that I saw people suggesting, also didn't work (but I'm not sure I've done it correctly), an all it shows is this PNG loaded, SVGs not

and this is the code for it

import { BackButton, BackIcon, HeaderDiv,
PeriodoTitle, SwitchButton, SwitchDiv, SwitchImg } from "./style";


type header = {
    title: string;
};

export default function PageHeader(
    {title}: header
) {
    return (
        <HeaderDiv>
            <BackButton>
                <BackIcon src={require('../../assets/Back.png')}/>
            </BackButton>

            <SwitchDiv>
                <SwitchButton>
                    <SwitchImg src={require('../../assets/goright.svg')}/>
                </SwitchButton>

                <PeriodoTitle>{title} Período</PeriodoTitle>
                
                <SwitchButton>
                    <SwitchImg src={require('../../assets/goleft.svg')}/>
                </SwitchButton>
            </SwitchDiv>
        </HeaderDiv>
    );

};

as you can see the arrow to go back is displayed normally as a png but all svg simply doesn't render, any suggestions ?

CodePudding user response:

Did you try this by any chance?

import SwitchLeft from '../../assets/goleft.svg'
// ...
<SwitchImg src={SwitchLeft}/>

https://www.freecodecamp.org/news/how-to-import-svgs-in-react-and-vite/

CodePudding user response:

If you are using vite for react app. You can use vite plugin called "vite-plugin-svgr"

Install it with

# yarn
$ yarn add vite-plugin-svgr

# npm
npm i vite-plugin-svgr

edit vite.config.js file

import { defineConfig } from 'vite' 
import react from '@vitejs/plugin-react' 
import svgr from "vite-plugin-svgr"; 
  
// https://vitejs.dev/config/ 
export default defineConfig({ 
  plugins: [svgr(), react()], 
})

And after that you can import any svg image as a react component like that

import { ReactComponent as IconMenuClose } from "../assets/images/icon-menu-close.svg";
  • Related