Ayyappa Gollu
Ayyappa Gollu

Reputation: 966

Uncaught Invariant Violation: Invalid hook call

i am new to react.

i am facing following issue while trying to build a functional component: Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component.

import React, {useState, useEffect} from "react"
import {render} from "react-dom";

const functionVersion = ()=>{
    const [name, setName] = useState("name");

    return(
        <div>     
            <label htmlFor="name">Name</label>       
            <input
             id="name"
             value={name}
             onChange= {e=>setName(e.target.value)}
             >
            </input>
        </div>
    )
}

render(functionVersion(), document.getElementById("root"))

may i know what is wrong with my hooks syntax ?

Upvotes: 1

Views: 1150

Answers (2)

Vencovsky
Vencovsky

Reputation: 31663

You can only use Hooks inside components.

Functional components are also a function, so still can call then as a normal function, but if you do that, it wont be a react component.

To render a functional component, you need to use JSX that will be converted to React.createElement(...).

Change:

render(functionVersion(), document.getElementById("root"))

to:

render(<FunctionVersion/>, document.getElementById("root"))

You also need to make the name of the functional component with the first letter in uppercase.

Upvotes: 2

AngelSalazar
AngelSalazar

Reputation: 3113

const FunctionVersion = ()=>{
    const [name, setName] = useState("name");

    return(
        <div>     
            <label htmlFor="name">Name</label>       
            <input
             id="name"
             value={name}
             onChange= {e=>setName(e.target.value)}
             >
            </input>
        </div>
    )
}

render(<FunctionVersion/>, document.getElementById("root"))

Upvotes: 2

Related Questions