Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid Component Element in React.JS

Tags:

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>
like image 367
whatoncewaslost Avatar asked May 16 '15 12:05

whatoncewaslost


People also ask

Can you React component without rendering?

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 Fragment is used in React?

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.

Can a Fragment have a key React?

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.

What is Fragment tag in React?

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.


1 Answers

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

like image 97
Oleksandr T. Avatar answered Sep 20 '22 11:09

Oleksandr T.