kilogram
kilogram

Reputation: 717

I can't create a React element by hand typing literal

I created 2 React elements: first is created traditionally, using react.createElement and second element - by hand typing literal(for educational purpose). I heard that React element is just a js object. First is rendering fine. Second is causing error.

Error: ReactDOM.render(): Invalid component element. This may be caused by unintentionally loading two independent copies of React.

What is wrong with second React element?

<script>


var first = React.createElement("h1", null, "Important Announcement");

var second = 
{
$$typeof: Symbol(React.element),
"type": "h1",
"key": null,
"ref": null,
"props": {"children": "Important Announcement"},
"_owner": null,
"_store": {}
}

ReactDOM.render(first, document.getElementById('root'));

</script>

Upvotes: 1

Views: 202

Answers (1)

AWolf
AWolf

Reputation: 8980

Changing $$typeof definition to $$typeof: Symbol.for('react.element') should fix your issue.

React requires it for security reasons as mentioned here.

Please have a look at the demo below or this jsbin.

var first = React.createElement("h1", null, "Important Announcement");

var second = {
  $$typeof: Symbol.for('react.element'),
  "type": "h1",
  "key": null,
  "ref": null,
  "props": {
    "children": "Important Announcement"
  },
  "_owner": null,
  "_store": {}
}

console.log(first, second)
ReactDOM.render(second, document.getElementById('root'));
<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>

<div id="root"></div>

Upvotes: 1

Related Questions