3

I'm trying to load an image asynchronously and only when it's been loaded, display it in a React app.

componentDidMount() {
    const img = new Image();
    img.onload = () => {
        this.setState({
            originalImage: img,
        });
    }
    img.src = './images/testImage.jpg'
}

render() {
    return (
       <main>
           {
              this.state.originalImage
           }
       </main>
    );
}

I'm getting below error:

Objects are not valid as a React child (found: [object HTMLImageElement])

I would like to know why this error is happening. Of course if I just add an <img> tag, it works fine.

Jaydeep
  • 1,686
  • 1
  • 16
  • 29
Scruffy
  • 444
  • 1
  • 6
  • 13

3 Answers3

4

React cannot directly display HTML Element. If you want to create elements programmatically you have to use functions provided by React.

componentDidMount() {
    const url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRYd74A26KhImI1w9ZBB-KvWUcasVnQRe_UOrdZPqI4GOIN0mC3EA';

    let img = React.createElement(
      "img",
      {
        src: url,
      },
    )
    this.setState({
      originalImage: img,
    })


    let divExample = React.createElement(
      'div',
      null,
      `Hello World`
    );
    this.setState({
      divExample: divExample
    })
}

render() {
    return (
      <div>
        <div>Hi</div>
        {
          this.state.divExample
        }
        <main>
          {
            this.state.originalImage
          }
        </main>
      </div>
    );
}

React parses jsx element like div, img, HelloWorld (custom) etc. and create React Elements out of it.

Sumith
  • 153
  • 8
1

As the error says, this.state.originalImage is an object. You probably are looking for it's src prop, which you can use like so:

 render() {
    return (
        <main>
          <img src={this.state.originalImage.src}/>
        </main>
    );
}
Clarity
  • 10,730
  • 2
  • 25
  • 35
  • It's a HTMLImageElement. I thought that we can keep such elements in a variable and then render them in React. In regular javascript, I could add this image object (HTMLImageElement) to the page with appendChild. – Scruffy Jul 18 '19 at 09:00
  • It would be `this.state.originalImage.attributes.src` – Michael Doye Jul 18 '19 at 09:20
  • @MichaelDoye where does it say that? https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement – Clarity Jul 18 '19 at 09:32
1

another idea is dangerouslysetInnerHTML - something like this ?

<div dangerouslySetInnerHTML={{ __html: this.state.originalImage.outerHTML }}/>}

gray
  • 798
  • 18
  • 31