I am using React with Webpack.
I have a React Component that takes a prop which is a url and displays the image.
Since React won't know the image url until runtime, can webpack still 'require' the image url?
import React, {Component} from 'react'
export default class Episode extends Component {
constructor(props){
super(props)
}
render(){
let imageStyle = {backgroundImage: 'url(' + this.props.episode.url +')'}
return (
<div className="episode">
<div className="image" style={imageStyle}>
<h2>{this.props.episode.category}</h2>
</div>
<h3>Episode {this.props.episode.number}</h3>
</div>
)
}
}
For reference, my images are located in:
src/assets/images
and my webpack is building to dist
For reference, Jumoels answer was almost there but you can't do an import statement inside a componentWillMount.
My Solution to this was as follows:
class YourComponent extends Component {
constructor(props){
super(props);
this.state = {
image: ""
};
}
componentWillMount(){
this.state.image = require('../../public/assets/img/' + this.props.img);
}
render() {
return(
<img src={this.state.image}/>
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With