0

I am a novice in ReactJS. I want to print out the image and text in the state object, but I do not know why it does not work when the system does not show any error. The following is my code

import React, { Component } from 'react';

class Asgn6 extends Component {
  constructor(){
    super();
    this.state={
      content:[
        {srcImg:"../img/1.png", text:"Black"},
        {srcImg:"../img/2.png", text:"Blue"},
        {srcImg:"../img/3.png", text:"Green"}
      ]
    }
  }
  add=() => {

  }
  render() {
    return (
        <div>
        {this.state.content.map((obj, index)=> {
          return (
          <div key={index}>
          <img src={require(obj.srcImg)} alt={obj.text}/>
          <p>{obj.text}</p>
          </div>
          );
        })}
          );
        <button onClick={this.add}>Add</button>
        </div>



    );
  }

}

export default Asgn6;
Alice
  • 181
  • 1
  • 2
  • 15

2 Answers2

3

The first rule you need to remember about automatic semicolon insertion is to keep whatever you return on the same line after return keyword. Otherwise this

return
  <div>
    <img src={require(obj.srcImg)} alt={obj.text}/>
    <p key={index}>{obj.text}</p>
  </div>

is equivalent to

return;
  <div>
    <img src={require(obj.srcImg)} alt={obj.text}/>
    <p key={index}>{obj.text}</p>
  </div>

Note, how semicolon is inserted after return.

Simple fix can be

return <div>
  <img src={require(obj.srcImg)} alt={obj.text}/>
  <p key={index}>{obj.text}</p>
</div>

or use parenthesis to group your returns:

return (
  <div>
    <img src={require(obj.srcImg)} alt={obj.text}/>
    <p key={index}>{obj.text}</p>
  </div>
)
dfsq
  • 182,609
  • 24
  • 222
  • 242
  • Thanks. I already fix as you told me but now I got the error "Cannot find module '.' " and it highlights the img tag. Is there something wrong with the img tag? – Alice Sep 20 '17 at 08:43
  • Did you set up webpack to load images like this? Take a look at this https://stackoverflow.com/questions/32612912/dynamically-add-images-react-webpack – dfsq Sep 20 '17 at 08:49
0
<img src={obj.srcImg} alt={obj.text}/>

just do this.

  • Thanks, but only the alt show up, the image is still nowhere to be found. It seems that require() gives me the error. The program works properly without require – Alice Sep 20 '17 at 11:27