1

I have a left-menu and when you click on a element, the sub-menu of the element appear.

But with my actual code, when a click on a element, all of my submenu appear.

I know my method is not right, but i don't know how to do :(

My example code :

import { useState } from 'react'

export default function Menu(){
 const [visibleSubCategorie, setVisibleSubCategorie] = useState(false)

 const Menu = [{
    name: 'Homme', link : '/homme-fr', subCategory: false
 }, {
    name: 'Femme', link : '/femme-fr', subCategory: [{
        name: 'haut', link : '/femme-haut-fr'
    },{
        name: 'bas', link : '/femme-bas-fr'
    }]
 },{
    name: 'Enfant', link : '/enfant-fr', subCategory: [{
        name: 'haut', link : '/enfant-haut-fr'
    },{
        name: 'bas', link : '/enfant-bas-fr'
    }]
 }]
 console.log("Menu -> Menu", Menu)

 return(
    <>
    {Menu.map(item=>
        <div>
            {item.subCategory ?
            <>
                <button type="button"  onClick={() => setVisibleSubCategorie(!visibleSubCategorie)}>{item.name}</button>
                {visibleSubCategorie && item.subCategory.map(subCategorys=>
                    <>
                        <p>{subCategorys.name}</p>
                    </>
                )}
            </>
            :
            <a href={item.link}>{item.name}</a>   
            }
        </div>
    )}
    </>
)

}``

example : when i click at the button "Femme" to see the sub-category of femme, it's like i click too on the button "Enfant".

I can create a composant and make the usestate "const [visibleSubCategorie, setVisibleSubCategorie] = useState(false)" inside and this composant inside the map but i know another method exist.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Does this answer your question? [React modal always take the last element of map function](https://stackoverflow.com/questions/59581998/react-modal-always-take-the-last-element-of-map-function) – Brian Thompson May 15 '20 at 13:26

2 Answers2

0

You are using the same piece of state to control all of your subCategories. A possible solution would be to useState as an array of string values for each subcategory.

const [visibleSubCategorie, setVisibleSubCategorie] = useState([])

setVisibleSubCategorie([...visibleSubCategorie, subCategorys.name])

Then check to see if that name exists in the array to know if you should show the subcategory.

{visibleSubCategorie.includes(subCategorys.name) && item.subCategory.map(subCategorys=>

You will then have to remove that item from the array when closing.

Kyler
  • 76
  • 1
  • 7
0

You could solve this using a method similar to what @Kyler suggested.

I suggest using a HOC, like this:

const setOpen = (setOpen, opened) => () => setOpen(!opened);

And then in your JSX:

onClick={setOpen(setVisibleSubCategorie, visibleSubCategorie)}

Note that in order for this to work, you'd have to have state for each of your sections.

Lior Pollak
  • 3,362
  • 5
  • 27
  • 48