React / 2 MIN READ
Menu Toggle
Toggle the menu visibility
From the original Fervor library. Examples may use older package versions.
How to Toggle a Menu Open and Closed in a React Application
Follow these steps to create a menu that can be toggled open and closed in a React application:
Step 1: Create a new functional component for the menu
First, create a new component for the menu. This component will manage its own state for toggling the menu open and closed.
import React, { useState } from 'react';
function Menu() {
// Add the component logic here
}
Step 2: Add state management for the menu’s open/closed state
Use the useState hook to manage the menu’s open/closed state. The useState hook takes an initial value for the state and returns an array containing the current state value and a function to update it.
const [isOpen, setIsOpen] = useState(false);
Step 3: Create a toggle function
Write a function to toggle the menu’s open/closed state. This function should update the isOpen state by negating its current value.
function toggleMenu() {
setIsOpen(!isOpen);
}
Step 4: Render the menu
Based on the isOpen state, conditionally render the menu content. You can use a ternary operator or a conditional rendering pattern to achieve this.
return (
<div>
<button onClick={toggleMenu}>Toggle Menu</button>
{isOpen ? <div className="menu-content">Menu Content</div> : null}
</div>
);
Step 5: Export the component
Export the Menu component so you can use it in other parts of your application.
export default Menu;
Here’s the complete Menu component code:
import React, { useState } from 'react';
function Menu() {
const [isOpen, setIsOpen] = useState(false);
function toggleMenu() {
setIsOpen(!isOpen);
}
return (
<div>
<button onClick={toggleMenu}>Toggle Menu</button>
{isOpen ? <div className="menu-content">Menu Content</div> : null}
</div>
);
}
export default Menu;
Now you can import and use the Menu component in other parts of your application, and it will manage its own open/closed state.