Im currently trying to import my Navbar into a new project. I created a Navbar using the state hook.
export default function Heading() {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<Navbar color="light" fixed="top" light expand="md">
<NavbarBrand href="/">reactstrap</NavbarBrand>
<NavbarToggler onclick={setIsOpen(!isOpen)} />
<Collapse isOpen={isOpen} navbar>
<Nav className="me-auto" navbar>
<NavItem>
<NavLink href="/components/">Components</NavLink>
</NavItem>
<NavItem>
<NavLink href="https://github.com/reactstrap/reactstrap">
GitHub
</NavLink>
</NavItem>
<UncontrolledDropdown inNavbar nav>
<DropdownToggle caret nav>
Options
</DropdownToggle>
<DropdownMenu end>
<DropdownItem>Option 1</DropdownItem>
<DropdownItem>Option 2</DropdownItem>
<DropdownItem divider />
<DropdownItem>Reset</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
</Nav>
<NavbarText>Simple Text</NavbarText>
</Collapse>
</Navbar>
</div>
);
}
I am importing this in my App.tsx like this
import Heading from "./modules/Heading";
export default function App() {
return (
<div className="App">
<Heading/>
</div>
);
}
But im getting this error
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
Does anyone know how to fix this?
The issue is highly likely with the onclick
in your NavbarToggler
component.
Usually in React, onclick
event handler usually takes in a FUNCTION, not a FUNCTION CALL. Therefore, you should change to
<NavbarToggler onClick={() => setIsOpen(currentState => !currentState)} />
This small change creates an arrow function that will do the same as before. However, the difference is that this is only a function definition, meaning it is not called yet (and is just existing)