Reputation: 2064
Lets say I have a bunch of local images that are part of my react project. I have a component that accepts props from higher up -- and one of the props is image name. So using , this could work. The tricky part is that I am using webpack, and I think thats why my images dont get displayed -- they arent pulled in. So before I had converted my component to use props, the image name was hardcoded, and worked like this:
<img src={require('../images/products/image-aqua.png')}/>
but now it looks as following, and doesnt work:
<img src={this.props.productImageUrl} />
Essentially, I am trying to stradle react "on the fly" image names and webpack packing concepts (I do know about webpack url-loader and file-loader) thank you
Upvotes: 0
Views: 795
Reputation: 1867
You should probably post your webpack so we can help you further. Your code above should work no problem.
Here is my webpack for img and such and it works as you are trying to use it.
{
test: /\.(jpg|jpeg|gif|png|tiff|svg)$/,
exclude: /\.glyph.svg/,
use: [
{
loader: 'url-loader',
options: {
limit: 6000,
name: 'image/[name].[ext]',
},
},
],
},
The only other issue you could be encountering is that your images aren't actually loaded when your component loads. Are you getting any errors or they just aren't showing?
class ProductList extends React.Component {
render() {
const product = Seed.products[0];
return (
<div className='ui unstackable items'>
<Product
id={product.id}
title={product.title}
description={product.description}
url={product.url}
votes={product.votes}
submitterAvatarUrl={`${product.submitterAvatarUrl}`}
productImageUrl={`${product.productImageUrl}`}
/>
</div>
);
}
}
class Product extends React.Component {
render() {
console.log("image name " + `${this.props.productImageUrl}`);
return (
<div className='item'>
<div className='image'>
<img src={`${this.props.productImageUrl}`} /> {/*this.props.productImageUrl*/}
</div>
<div className='middle aligned content'>
<div className='header'>
<a>
<i className='large caret up icon' />
</a>
{this.props.votes}
</div>
<div className='description'>
<a href={this.props.url}>
{this.props.title}
</a>
<p>
{this.props.description}
</p>
</div>
<div className='extra'>
<span>Submitted by:</span>
<img
className='ui avatar image'
src={`${this.props.submitterAvatarUrl}`}
/>
</div>
</div>
</div>
);
}
}
ReactDOM.render(
<ProductList />,
document.getElementById('content')
);
...
import aqua from '../images/products/image-aqua.png';
import daniel from '../images/avatars/daniel.jpg';
export default window.Seed = (function () {
function generateVoteCount() {
return Math.floor((Math.random() * 50) + 15);
}
const products = [
{
id: 1,
title: 'Yellow Pail',
description: 'On-demand sand castle construction expertise.',
url: '#',
votes: generateVoteCount(),
submitterAvatarUrl: daniel,
productImageUrl: aqua,
},
Upvotes: 1