September 23, 2023

How to add images in react?

In react, we can’t add image straight as below which we used to do in HTML

<img src='pathtoimage/img.png' />

Because jsx doesn’t understand it. we need to tell react externally that you need to import image

let’s do it,

Set up react app using below command

npx create-react-app my-app

As we know , above command setup react project with webpack

so, we can import image as module like below

import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
  return (
    <div className="App">
      <img src={logo} />
    </div>
  );
}
export default App;

As you can see above we imported the logo.svg as a module and assign it to the src attribute of the img tag. You can import any type of image for eg. png, jpg etc

If you don’t want to import image then there is also provision to add image in src URL using require function

like below

import React from 'react';
function App() {
  return (
    <div className="App">
      <img src={require('./logo.svg')} />
    </div>
  );
}
export default App;

As you can see above we have added require function to resolve path of the image. Same we can import any type of image for eg. png,jpg etc using require function

Importing .svg image as component

From react@16.3.0, we can use .svg image as component directly instead of adding in the src attribute, like below

import React from 'react';
import { ReactComponent as Logo } from './logo.svg';
function App() {
  return (
    <div className="App">
      <Logo />
    </div>
  );
}
export default App;

As you can see in above example, we uses Logo as reactComponent .

ReactComponent in the import, tells react that you want to load SVG image as a component instead of a file.

Adding background image in css

In css, still the same way to add background image using url(),

like below

.Logo {
  background-image: url(./logo.png);
}