Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a new Image() in react

I am trying to keep an image from reloading when the state changes. The below image variable is passed into the props of a custom react component.
var img = new Image(); I've already set the src, title, desc, etc.

So my question is. In the custom react component, how do I take the image object (now a prop titled img) and display it in the render function?

I've already tried

render: function(){
  return <div>{this.props.img}</div>
}

But I keep getting a DOM elements are not valid child of React components error.

like image 817
Heath Avatar asked Feb 26 '16 16:02

Heath


2 Answers

I think what you're trying to do is create a new DOMNode of the Image variety and render that as a child of the <div>. If that's right, you're doing something React isn't made to do. Two options:

Option 1 (Best): Render the image tag in your React component template

render: function() {
    return (
        <div>
            <img src={'url-to-your-image'} />
        </div>
    );
}

Option 2 (Not as good): Render the image as an HTML string entity

renderHTML: function() {
    return {
        __html : '<img src="url-to-your-image" />'
    }
},

render: function() {
    return (
        <div dangerouslySetInnerHTML={this.renderHTML()} />
    );
}

Hope that helps!

like image 165
David Hariri Avatar answered Oct 23 '22 21:10

David Hariri


The Image constructor returns an HTMLImageElement interface.

So to render your img prop, which as you mention was created using var img = new Image(), you basically have to create an element and render it.

You can do this via JSX

const YourComponent = ({img}) => <img src={img.src} alt="foo" />

or

Use the React.CreateElement syntax if you need to do it programmatically.

const YourComponent = ({img}) => {

  const myImage = React.createElement("img", {
     src: img.src,
     // any other image attributes you need go here
  }, null);

  return (
    {myImage}
  );
}

like image 44
Joe Seifi Avatar answered Oct 23 '22 22:10

Joe Seifi