Home > Net >  Div appear and disappear onclick in React hooks
Div appear and disappear onclick in React hooks

Time:10-12

I want an effect like this (before onclick)(after oncilck).Just click on which div to make it disappear, and then let the div that disappeared before show again.

Here is the data code(just an array). I want the "show" variable in the data to control whether to display.But I don't know how to implement the destructuring assignment to the array in the click function.

Thank you for your answer!

const leftBarData=
[{
    name:"关于音乐",
    color:"bg-music-color",
    icon:<div className="iconMusicSize">
        <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
            blahblah
        </svg>
    </div>,
    link:"/music",
    number:0,
    show:true,
},
    {
        name:"关于编程",
        color:"bg-code-color",
        icon:<div className="iconSize">
            <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                blah
            </svg>
        </div>,
        link:"/code",
        number:1,
        show:true,
    },
    {
        name:"关于设计",
        color:"bg-design-color",
        icon:<div className="iconSize">
            <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                blah
            </svg>
        </div>,
        link:"/design",
        number:2,
        show:false
    },
    {
        name:"关于本人",
        color:"bg-about-color",
        icon:<div className="iconSize">
            <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                blah
            </svg>
        </div>,
        link:"/design",
        number:3,
        show:true
    }
]

Here is the map.

const [statusData,setStatusData]=useState(leftBarData)
const changeBar=(pars)=>
    {
        how to achieve it
    }

<div className="flex fixed">
        {statusData?.map((index,i)=>(
            <Link to={index.link}>
                <div className={` ${index.color} ${index.show?"":"hidden"} w-99 h-screen pt-9 `} onClick={()=>changeBar(index)}>
                    <div className="flex flex-col h-full items-center justify-between">
                            {index.icon}
                        <div className="-rotate-90 -translate-y-full mb-10">
                            <div className="h3 text-white whitespace-nowrap">{index.name}</div>
                        </div>
                    </div>
                </div>
            </Link>
        ))}
    </div>

CodePudding user response:

You can map() your state data to toggle show property of clicked element like this:

const changeBar = pars => {
    setStatusData(data => data.map(item => (
        item === pars
        ? item
        : {
            ...item,
            show: !item.show
        }
    ));
};
  • Related