1

Started Learning React recently (and already posting on stackoverflow :P),
Now this is in my App.js file:

import React from "react";

export default function App(props){
    return (
            <img src={"./images"+props.img} alt="something" />
    )
}

And this is in my index.js file:

import React from "react"
import ReactDOM from "react-dom"
import App from "./App"

ReactDOM.render(<App img="katie-zaferes.png"/>, document.getElementById("root"))

And nothing shows up (actually "something" shows up since it's the alt text), how do I make it work?

I am working in an app created using npx create-react-app.
Here is how the project looks:
enter image description here
I wanna be able to take the name of the image as argument in the App.js and display it. I know beforehand that the image lies in the image folder
Tried to do a project from Scrimba React course, link to which is below:
https://scrimba.com/learn/learnreact/project-pass-props-to-card-component-co2094669b9fe6bf481f857ae

Yash Patil
  • 33
  • 1
  • 4
  • 1
    your src is `"./images"+props.img` so when props.image is `"katie-zaferes.png"` the actual value for src will be "./imageskatie-zaferes.png"` , what you shouldve used for src is `"./images/"+props.img`, this should work assuming you hosted the images correctly – Chris Li Aug 08 '22 at 20:54
  • @ChrisLi corrected that and it still won't work. ademclk 's solution posted below works, by using require() function – Yash Patil Aug 08 '22 at 20:59
  • Yes, with React you cannot reference the project's file system in a `src` attribute directly because it's client-side code. If you have used `create-react-app` you can put static assets in the `public` folder. For instance if you create an `images` folder in there and put the image inside, your original code (plus missing slash) will work, however you need to remove the period at the start: `src={"/images/" + props.img}` –  Aug 08 '22 at 21:09
  • This is useful for SEO reasons. If you require an image instead it gets webpacked and a random hex id as filename. This is fine for design elements like icons, not so much for actual content. (still, with a standard react app SEO won't work either way) –  Aug 08 '22 at 21:12

0 Answers0