How do I import an SVG to a class-based child-component in React?

Viewed 4985

I am able to import the svg in the parent component App.js(in the src folder) but not in the child component Home.js(src/components/Home.js)

When I import directly into the parent component the svg displays perfectly but if I import in the child component it says

Module not found: Can't resolve './img/BulbOn.svg' in 'E:\Website Work\Current Work\parsa_ventures\src\components'

   import './App.css'
   import Home from './components/Home'
   function App() {
     return (
        <div>
            <Home />
        </div>
    )
   }

   export default App 
   import BulbOn from './img/BulbOn.svg'

   class Home extends React.Component {
     render() {
         return (
            <div>
                <img src={BulbOn} alt="text" />
            </div>
         )
     }
   }

   export default Home

I am new to react so I am wondering if I can easily import svg in child component without having to use props.

my folder structure paths,

Website Work/Current Work/parsa_ventures/src/App.js (Parent)
Website Work/Current Work parsa_ventures/src/components/Home.js (Child) Website Work/Current Work/parsa_ventures/src/img/BulbOn.svg (Image)
i put the react boilerplate inside parsa_ventures, so thats where the src is containing all the files

2 Answers

you are using ./img which means E:\Website Work\Current Work\parsa_ventures\src\components\img\BulbOn.svg should exist. please check your paths,

you need to put ./../img/BulbOn.svg should work.
try below code,

import BulbOn from './../img/BulbOn.svg'

   class Home extends React.Component {
     render() {
         return (
            <div>
                <img src={BulbOn} alt="text" />
            </div>
         )
     }
   }

   export default Home

Check your path from the child component as it seems you have missed one folder and then try. Also, you can pass the svg image from parent to child component.

import React from 'react';
import Logo from '../../logo.svg';

class Test extends React.Component {
    render() {
        return (
            <div>
                <img src={this.props.url} alt="text" />
            </div>
        )
    }
}

export default Test

In parent component, pass svg path url to child component - Test.

<Test url={Logo} />
Related