Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack require dynamic image in a React component

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

like image 273
Terence Chow Avatar asked Nov 08 '22 22:11

Terence Chow


1 Answers

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}/>
        )
    }
}
like image 188
mjudd Avatar answered Nov 14 '22 22:11

mjudd