Search code examples
reactjsreact-dom

How to define a img tag inside a React.createElement() in React?


Learning react and came across a scenario where I would want to define a 'img' tag inside React.createElement(). I have tried below syntax, but I am sure its a wrong method:

function Greeting() {
  return (
    <div>
      <Person />
      <Message />
    </div>
  );
}

const Person = () => {
  <h2>Its an Image</h2>;

  return React.createElement(
    "img",
    {},
    "https://images-eu.ssl-images-amazon.com/images/I/81l3rZK4lnL._AC_UL200_SR200,200_.jpg"
  );
};

The error which I get is as below:

Error: img is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.
▶ 15 stack frames were collapsed.
Module.<anonymous>
E:/REACT_APP/tutorial/src/index.js:43
40 | return <p>Follow the white rabbit </p>;
41 | };
42 | 
> 43 | ReactDom.render(<Greeting />, document.getElementById("root"));
44 | 

Please suggest,


Solution

  • The arguments for React.createElement is as follows (as seen in the docs):

    React.createElement(
      type,
      [props],
      [...children]
    )
    

    The last argument is the children, but when you create an image element, it should have no children (ie: it's a void element tag like the error mentions). Currently, you're adding the image source as the children, giving equivalent to:

    <img>
      https://images-eu.ssl-images-amazon.com/images/I/81l3rZK4lnL._AC_UL200_SR200,200_.jpg
    </img>
    

    Instead, you need to specify the img source in the props of the created element, and pass null for the children (undefined/null would work here, so not supplying a 3rd argument will also work):

    React.createElement(
      "img",
      {src: "https://images-eu.ssl-images-amazon.com/images/I/81l3rZK4lnL._AC_UL200_SR200,200_.jpg"},
      null
    );
    

    As a side note, the content that gets rendered is the content you return from your component. The <h2>Its an Image</h2>; isn't being returned or used anywhere, it's like writing 1 + 2 inside of a regular function, it will evaluate to 3, but won't do much other than that unless you do something with it.