camcam
camcam

Reputation: 2625

React complains about invalid function component

I have a problem with a mini react app.

The error says: "Invalid hook call. Hooks can only be called inside of the body of a function component".

The function accepts an argument and returns a React element, so it should be a valid component according to the docs. React and ReactDOM are the same version. If you comment out the line with hook, the error is gone and the component renders.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Small Test</title>
    </head>
    <body>
        <div id="container"></div>
        <script
            src="https://unpkg.com/react@16/umd/react.development.js"
            crossorigin
        ></script>
        <script
            src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
            crossorigin
        ></script>
        <script>
            function MyComponent(props) {
                const [state, setState] = React.useState("");
                return React.createElement("span", null, "Hello Component!");
            }

            const container = document.getElementById("container");
            ReactDOM.render(MyComponent(), container);
        </script>
    </body>
</html>

How to fix it?

Upvotes: 0

Views: 36

Answers (2)

simbathesailor
simbathesailor

Reputation: 3687

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Small Test</title>
    </head>
    <body>
        <div id="container"></div>
        <script
            src="https://unpkg.com/react@16/umd/react.development.js"
            crossorigin
        ></script>
        <script
            src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
            crossorigin
        ></script>
        <script>
            function MyComponent(props) {
                const [state, setState] = React.useState("");
                return React.createElement("span", null, "Hello Component!");
            }

            const container = document.getElementById("container");
            ReactDOM.render(React.createElement(MyComponent), container);
        </script>
    </body>
</html>

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 85012

ReactDOM.render(MyComponent(), container);

You're calling MyComponent as a function, not creating an element from it. You'll need to change it to:

ReactDom.render(React.createElement(MyComponent), container);

The equivalent with JSX would be:

ReactDom.render(<MyComponent />, container);

Upvotes: 1

Related Questions