简体   繁体   中英

Show or hide a React component rendered from an array, only a specific one

I am rendering some elements from an array. For each of these elements a component should be rendered if and only if a value in state is true. so it is like this:

element.map(item => {
   <div>{item.name}</div>
   { state.property && <MyComponent /> }
})

The problem is, this component should be rendered when I hover the mouse over the <div> element. But when I hover and the state.property value gets true, all these components are shown. Not just the specific one.

I appreciate your help. Thanks.

If you only want the hovered div to show, then the best solution would probably be better to have a separate component altogether. Inside that component have a new state that changes on hover

 import { useState } from "react"; import MyComponent from "./MyComponent" function HoveredComponent (itemName) { const [hovered, setHovered] = useState(false); return ( <> // remember JSX needs to be all within a node <div onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} >{itemName}</div> { hovered && <MyComponent/> } </>) } export default function App () { var element = []; return ( element.map(item => <HoveredComponent name={item.name}/>) ) }

Thank you guys for your answer. What I have done finally is: For <MyComponent /> I added a class to set its display to none or block. Then inside the array element I have a field which can be whether true or false. The onMouseOver event will pass the index of that element, accordingly the component class will be assigned for that particular element. Hope it helps others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM