skip to Main Content

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.

4

Answers


  1. Chosen as BEST ANSWER

    Thanks for answers which helped me

    Solution was moving button.png file from public folder to src/images

    and edited HelloButton.js to

    import React from "react";
    import button from "../images/button.png"
    
    function HelloButton() {
      return (
        <a href="">
          <img
            style={{ height: "50px" }}
            alt=""
            src={button}
          />
        </a>
      );
    }
    
    export default HelloButton;
    

  2. This is the right way to import image in src

    import React from "react";
    import BUTTON fro "./button.png" // correct absolute path
    
    function HelloButton() {
      return (
        <a href="">
          <img
            style={{ height: "50px" }}
            alt=""
            src={BUTTON}
          />
        </a>
      );
    }
    
    export default HelloButton;
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
  4. import image like that

    import image from "./assets/image/icon.jpg"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search