1
votes

I want to close all other open Submenu when the user opens another Submenu. Here my code is doing on clicking its shows submenu and on another click, it hide. but I want to do it like when click shows current submenu and hide previous open submenu. I am using State Hooks to change the state.

Menu.jsx

import React from 'react';
import SubMenu from './SubMenu';

const Data = [
    {
        title : 'One',
        subMenu:[
            { title: 'One-One' },
            { title: 'One-two' }
        ]
    },
    {
        title : 'Two',
        subMenu:[
            { title: 'Two-One' },
            { title: 'Two-two' }
        ]
    },
    {
        title : 'Three',
        subMenu:[
            { title: 'Three-One' },
            { title: 'Three-two' }
        ]
    },

]

const Menu = () => {
    return (
        <div>
            {
                Data.map( (item , index) => {
                    return <SubMenu  item={item} key={index}/>
                  
                })
            }
        </div>
    )
}

export default Menu

SubMenu.jsx

import React, { useState } from 'react';

const SubMenu = ( {item}) => {
    const [child , setChild] = useState(false);

    function openChild() {
        setChild(!child);
    }


    return (
        <div>
            <ul onClick = { () => openChild() }>
                <div>
                {item.title}
                </div>
               <div>
               {
                   child && item.subMenu.map((item, index)=>{
                        return <li>{item.title}</li>
                    })
                }
               </div>
               
            </ul>
        </div>
    )
}

export default SubMenu;
When you click the sub-menu you have to set is as 'active' with your State. Try checking this for example: stackoverflow.com/questions/63258663/…Steffano Festa
I want to close the submenu of the previous opened menu when I clicked on another menuAmar Kumar Amar
Understood that, but it was pretty easy to find 'helps' on google, even inside here. glSteffano Festa