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;
2
  • Is Add button showing up ? Commented Sep 20, 2017 at 8:26
  • Yes, the button shows up but there's no img and text Commented Sep 20, 2017 at 8:29

2 Answers 2

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>
)
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Did you set up webpack to load images like this? Take a look at this stackoverflow.com/questions/32612912/…
0
<img src={obj.srcImg} alt={obj.text}/>

just do this.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.