0

I have a React app but when I try and render a PNG file in the "src" folder, I get the following on the Google Chrome browser: enter image description here

There is no Public folder in my project, so I am unable to place the image file there. The following is my code when loading the image:

enter image description here

What can I do instead?

Many thanks!

  • I don't think you can import an image outside of your CRA project, unless you change project webpack config. Is there a reason that you do not have a `public` directory? You could upload it on a server and put the URL as `src`. – c0m1t Aug 07 '22 at 16:48
  • Please post code, not images of code. – kennarddh Aug 07 '22 at 16:49
  • This is not a CRA project, but rather a Splunk create project: and a Public folder is not created by default: https://splunkui.splunk.com/Create/AppTutorial – Patrick O'Rourke Aug 07 '22 at 16:58
  • 1
    Does this answer your question? [Load local images in React.js](https://stackoverflow.com/questions/44154939/load-local-images-in-react-js) – Konrad Aug 07 '22 at 16:59
  • Yes, this solved my issue: import React from "react" import splunklogo from './splunk-logo.png'; export default function NavbarComponent() { return ( ) } – Patrick O'Rourke Aug 07 '22 at 17:10

1 Answers1

0

You can solve that using 2 simple ways, one of them is to take the image address as a constant, the other one can be passing the address directly. To clarify the images cannot be outside(no absolute path) of your project, i.e. the direction to your image should be as follows ../splunk-logo.png


import "./styles.css";
const image = require("./Landscape.jpg");

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {/* One way */}
      <img src={image} alt="Landscape img" height="200px" />
      <br />
      {/* Second way */}
      <img src={require("./Landscape.jpg")} alt="Second Land" height="200px" />
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}


Test Here

KrLiTs
  • 151
  • 7