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!

5
  • 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. Commented Aug 7, 2022 at 16:48
  • Please post code, not images of code. Commented Aug 7, 2022 at 16:49
  • This is not a CRA project, but rather a Splunk create project: and a Public folder is not created by default: splunkui.splunk.com/Create/AppTutorial Commented Aug 7, 2022 at 16:58
  • 1
    Does this answer your question? Load local images in React.js Commented Aug 7, 2022 at 16:59
  • Yes, this solved my issue: import React from "react" import splunklogo from './splunk-logo.png'; export default function NavbarComponent() { return ( <nav> <img src={splunklogo} alt="Splunk-Logo"/> </nav> ) } Commented Aug 7, 2022 at 17:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.