2

As part of a personal project, I have to create an image gallery. For every image (miniature) that is clicked in the gallery, I want the chosen image to appear in a larger size on the page. I have been trying to do this by passing the desired image's address as a prop to my ImageOnView component, like so:

<ImageOnView imgSrc = {this.state.imageLarge}/>

Inside my ImageOnView component, however, I'm having trouble displaying the image using the require() method. Right now it looks like this:

class ImageOnView extends Component {
  render() {
    //This alert displays the image source as expected
    alert(this.props.imgSrc);
    return (
      <img id = "image-large" src = {require(this.props.imgSrc)}/>
    );
  }
}

I get the following error on my webpage: "Error: Cannot find module ".""

How do I go about resolving this issue? Thanks in advance.

Akrion
  • 18,117
  • 1
  • 34
  • 54
Rodrigo Veiga
  • 125
  • 1
  • 1
  • 8

4 Answers4

3

Just try

src={require('' + this.props.imgSrc)}
Suman Kundu
  • 1,702
  • 15
  • 22
0

Since you are using Webpack as a bundler in runtime, require can't use a variable name like this. It should accept a resolvable path, ie a string here. So, you can require the image in the parent instead of the child and use the resolved path:

class App extends Component {
  state = {
    imageLarge: require( "./somedir/some.jpg" ),
  };

  render() {
    return (
      <div>
        <ImageOnView imgSrc={this.state.imageLarge} />
      </div>
    );
  }
}

class ImageOnView extends React.Component {
  render() {
    // This alert displays the image source as expected
    alert( this.props.imgSrc );
    return (
      <img id="image-large" src={this.props.imgSrc} />
    );
  }
}
devserkan
  • 16,870
  • 4
  • 31
  • 47
0

Can also do like this:-

import React from 'react';

function index({title, image, rating}) {
   return <div>
     <img alt="img" src={require("" + image)}></img>
   </div>;
}

export default index;
Ajay jangid
  • 711
  • 9
  • 9
-1

require() is used to import a module or file. So to get an imageLarge from another file you might want to

const imageLarge = require(path) 

or es6 version:

import imageLarge from 'path'

in the img tag you just need to provide a src attribute with imageLarge in component it would look something like:

const imageLarge = require(path) 

<ImageOnView imgSrc = {imageLarge}/>

class ImageOnView extends Component {
  render() {

    return (
      <img id = "image-large" src = {this.props.imgSrc}/>
    );

  }
}