Error: Invalid hook call. Hooks can only be called inside of the body of a function component. (w/ Reactstrap)

dimas hermanto :

Guys i know this error has asked many times in here, but i still really confused about this. So i tried to call the Navbar component below,

import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink} from 'reactstrap';

const [collapsed, setCollapsed] = useState(true);
const toggleNavbar = () => setCollapsed(!collapsed);


var mainNavbar1= () => {

return(
    <div className = "mt-2">
        <Navbar color="faded" light>
        <NavbarBrand href="/" className="mr-auto">Welcome!</NavbarBrand>

        <NavbarToggler onClick={toggleNavbar} className="mr-2" />

        <Collapse isOpen={!collapsed} navbar>
            <Nav navbar>
            <NavItem>
                <NavLink href="/components/">Home</NavLink>
            </NavItem>
            <NavItem>
                <NavLink href="/components/">About</NavLink>
            </NavItem>
            <NavItem>
                <NavLink href="/components/">Contact Me</NavLink>
            </NavItem>
            <NavItem>
                <NavLink href="/components/">Components</NavLink>
            </NavItem>
            <NavItem>
                <NavLink href="https://github.com/reactstrap/reactstrap">GitHub</NavLink>
            </NavItem>
            </Nav>
        </Collapse>

        </Navbar>
    </div>
);
}

export default mainNavbar1;

Inside the main component 'App',

import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Alert, Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink , Jumbotron,                 
Button, Container, Row, Col} from 'reactstrap';
import {mainNavbar1} from './mainNavbar';

var underDevelopmentAlert = () => {
   alert("Page under development!!");
}


var App = () => {

   return (
    <mainNavbar1/>
   )

}

And i got the error above. i already read the rules of Hooks and still got this. I'm pretty sure i'm already follow everything correctly.. Am i missing something ? (The Navbar component is copied straight from Reactstrap official website)

Jayce444 :

Firstly, React components MUST start with a capital letter, no exceptions.

Secondly, your hooks are not inside the component, they're only inside the file which your component is in. You need to actually put them IN the component definition. Like so:

const MainNavbar1 = () => {

    const [collapsed, setCollapsed] = useState(true);
    const toggleNavbar = () => setCollapsed(!collapsed);

    return(...)
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=279040&siteId=1