Toggling Dropdown Menu

Reetah Reetah
3 min read

Table of contents

Scenario is: onClick of a dropdown, I want to display something and onClick of another dropdown I want to display a different content from the first dropdown: Check it out here on codesandbox : Dropdown menu


First, declare a state for the dropdown/button


 import React, {useState} from 'react';
const [dropdownMenu, setDropdownMenu] = useState(false)

Next, write a function where you toggle the state of the dropdown to open or close where open is true and close is false according to the already declared state above.

const handleDropdown = () => {
setDropdownMenu(!dropdownMenu) 
}

Go ahead and call the function where the dropdown is declared.

onClick = {handleDropdown()}

Next, do a conditional rendering of what you want to show when you toggle using the declared state and the logical && operator / ampersand which will show the content of the dropdown if the state is true(toggled).

{ dropdown &&(
 <h2> I am Reetah </h2>
)}

Now, I want to render the same content

<h2> I am Reetah </h2>

in the next dropdown but if i try doing it this way,

{ 
dropdown &&(
 <h2> I am still Reetah </h2>
)}

the first dropdown will remain open and I do not want that.

What I want is for the first dropdown to close when the second dropdown is toggled open.

To solve this, go back to the function that toggles the state of the dropdown from false to true and pass in an index as a parameter

It could be index or anything I’ll use index in my case



const handleDropdown = (index) {

//write an if statement to check if the already declared state is equals to the passed parameter

if(dropdownMenu === index) {

//set the state to an empty string to prevent the dropdown from opening / closing the dropdown when another dropdown is clicked

setDropdownMenu(“”)

//write an else statement that’ll take the setState and accept the passed parameter so as to show the content in the component that you want to render depending on the passed index when you call the function.


} else {
    setDropdownMenu(index)

  }

}

When put together you should have this :

const handleDropdown(index) {
   if(dropdownMenu === index){
     setDropdownMenu("")
   } else {
     setDropdownmenu(index)
}

Go ahead and pass in an index to the called function in your dropdown

onClick={handleDropdown("0")}

In the conditional renderer, check if the state is equals to the passed index in the called function and use the double ampersand or logical operator to tell what is to be rendered.

{(dropdown === "0"  && (
    <h2> I am Reetah</h2>
)}

Check it out here on codesandbox : Dropdown menu

1
Subscribe to my newsletter

Read articles from Reetah directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Reetah
Reetah

I am here on @hashnode, to learn and share.