I've been going through a react.js tutorial, with a simple hello world example. I can't find a reason why the following shouldn't work, but I keep getting this error.
Uncaught Error: Invariant Violation: React.render(): Invalid component element.
I have the following code. It seems to work if I do React.createElement, but not for the JSX elements.
<!doctype html>
<html>
<head>
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script type="text/jsx">
document.body.onload = function(){
console.log("shuff")
var HelloWorld = React.createClass({
render: function(){
return <div>Hello, Ian Shuff!</div>;
}
});
React.render( new HelloWorld(), document.getElementById("test"))
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
TL;DR you can (and should) create React components that render nothing and use them to manage data and state in your app, in order to have components that are reusable and composable for real.
Why do we use fragments in React? React fragments serve as a cleaner alternative to using unnecessary divs in our code. These fragments do not produce any extra elements in the DOM, which means that a fragment's child components will render without any wrapping DOM node.
We can use React fragments to render lists to avoid the creation of extra div because fragments can also have keys that help React identify the updated or deleted elements.
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
You should pass to render <HelloWorld />
, not new HelloWorld()
React.render(<HelloWorld />, document.getElementById("test"))
Example
jsx-in-depth
Or you can use React.createElement
, like so
React.render(React.createElement(HelloWorld, null), document.getElementById("test"))
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With