Image is not shown from functional component to class component in React.js

My button.png file is in the public folder.

HelloButton.js in src/components:

import React from "react";

function HelloButton() {
  return (
    <a href="">
      <img
        style={{ height: "50px" }}
        alt=""
        src="/button.png"
      />
    </a>
  );
}

export default HelloButton;

Header.js in src/components:

import React, { Component } from "react";
import HelloButton from "./HelloButton";

export default class Header extends Component {
  render() {
    return (
     <div>
       <HelloButton />
     </div>
    );
  }
}

Even though there are no errors, but the image is not visible in the result.

>Solution :

The reason why the image is not showing up might be because of the incorrect path that is being used to access the image in the HelloButton component. Since you are trying to access the button.png file from the public folder, you need to use the absolute path for the image.

Change the code for the HelloButton component like below, here process.env.PUBLIC_URL mentions the absolute path to the public folder:

import React from "react";

function HelloButton() {
  return (
    <a href="">
      <img
        style={{ height: "50px" }}
        alt=""
        src={process.env.PUBLIC_URL + "/button.png"}
      />
    </a>
  );
}

export default HelloButton;


also as @Hithesh k mentioned make sure to use right way of import image in react

Leave a Reply