How to import image(SVG or PNG) in React using Create React App

3.2k views Asked by At

For example I have this <i> for Icon element

<i style={{ backgroundImage: `url(${'./images/names/Mike.svg'}` }}/>

I know I can import an image by importing them individually according to this post

but it's not feasible in my case since I need to import a lot of them.

Is there a workaround to make this possible in Create React App?

Edit: I'm currently doing this

backgroundImage: `url(${require(`./images/names/${name}.svg`)})`

but still not working, unless I hard code the name

backgroundImage: `url(${require(`assets/images/names/Mike.svg`)})`

which is not viable in my case.

1

There are 1 answers

2
bolarson On BEST ANSWER

Here are three ways to import an image (SVG and PNG) into a React project. You can use either file type with all three options.

  1. Import image and use it in a src attribute.
  2. Import image and use it in a style attribute.
  3. Dynamically insert into a require function.

See examples below:

import React from 'react';
import backgroundImg from '../assets/images/background.png';
import logoImg from '../assets/images/logo.svg';

const Test = props => {

     const imageLink = 'another.png'
     // const imageLink = props.image
     // You can loop this component in it's parent for multiple images.

     return (
         <div>
              <img src={logoImg} style={{ width: '200px', height: '45px' }} />
              <div style={{ width: '100%', height: '100%', backgroundImage: `url(${backgroundImg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundSize: 'cover', position: 'fixed'}} />
              <img width={900} height={500} alt="test img"  src={require(`../assets/images/${imageLink}`)}/>
         </div>
     )
}

export default Test