Webpack requires dynamic image in the React component

I am using React with Webpack.

I have a React component that takes a prop, which is a URL and displays an image.

Since React will not know the URL of the image until runtime, can webpack "require" the URL of the image?

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 in:

src/assets/images

and my web package is built on dist

+5
source share
2 answers

For reference, the Jumoels answer was almost yours, but you cannot execute the import statement inside componentWillMount.

My solution 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}/> ) } } 
+1
source

You can use import() to dynamically load images. Then in componentDidMount you can do something like the following:

 import('path/to/images/' + this.props.episode.url).then(function(image) { this.setState({ image: image }); }).catch(function(err) { // Do something }); 

In your render function, you can render a placeholder image, for example a transparent gif , until this.state.image contains something valid.

 render() { const imageSource = this.state.image ? this.state.image : "data:image/gif;base64,R0lGODlhAQABAAAAACw="; return <img src={imageSource} />; } 
0
source

Source: https://habr.com/ru/post/1239802/


All Articles