I am trying to display some products. The data is displayed fine. Both the name and the price. The problem comes when I try to display the product images. They appear as broken links. I teach the code
This is the Product Component.
import { Component } from 'react'
class Producto extends Component {
render() {
const producto = this.props.producto
return(
<div>
<img alt={producto.name} src={producto.img} />
</div>
)
}
}
The Products component
import { Component } from 'react'
class Productos extends Component {
render() {
const { productos, agregarAlCarro } = this.props
return(
<div>
{productos.map(producto =>
<Producto
agregarAlCarro={agregarAlCarro}
key={producto.name}
producto={producto}
/>
)}
</div>
)
}
}
And finally this is the App component. This is where the product data comes from.
import { Component } from 'react'
import Productos from './components/Productos'
class App extends Component {
state = {
productos: [
{name: 'Tomate', price: 1.50, img:'images/tomate.jpg'},
{name: 'Lechuga', price: 1.20, img:'images/lechuga.jpg'}
]
}
render() {
const { productos, agregarAlCarro } = this.props
return(
<div>
<Productos
agregarAlCarro={() => console.log("No hago nada") }
productos={this.state.productos}
/>
</div>
)
}
}
These are the three components that I have in my application. The folder structure is this.
Edit: I have tried with a url of an image that I have taken from wikipedia and it has worked. But with the images in the folder it doesn't work.
Your code doesn't work because your images are stored in your react js development folder, so by calling "images/tomato.jpg" your code tries to retrieve this path from the folder containing your React generated app.js in your public folder.
If you want to recover the image that is stored in your development folder, you must import it in your file, leaving your code as follows.
I hope I have helped you, greetings.