Search code examples
reactjstarget

OnMouseEnter in React on multiple divs doesn't work properly


I have a problem with onMouseEnter in React. I want to expand just one card, and when I hover over one, each one is expanded in the same time. Please, help.

export default function Modules() {

  const [isShown, setIsShown] = useState(false);

  return (
    <>
      <h5>title</h5>
      <Card>
        <div
          onMouseEnter={() => setIsShown(true)}
          onMouseLeave={() => setIsShown(false)}
        >
        <p>Tele</p>
        {isShown && (
          <div onMouseEnter={() => setIsShown(true)} onMouseLeave={() => setIsShown(false)}>
         <p>Logo</p>
         </div>
         </div>
        )}
      </Card>
           <h5>Title2</h5>
      <Card>
        <div
          onMouseEnter={() => setIsShown(true)}
          onMouseLeave={() => setIsShown(false)}
        >
        <p>Tele</p>
        {isShown && (
          <div onMouseEnter={() => setIsShown(true)} onMouseLeave={() => setIsShown(false)}>
         <p>Logo</p>
         </div>
         </div>
        )}
      </Card>```

Solution

  • That happens because you're using the same state. If ifShown is true all the cards will show.. You can create an independent Card Component that manages his own state.

    export const CardWrapper = ({ title}) => {
       const [isShown, setIsShown] = useState(false);
    
       return (
          <>
          <h5>{title}</h5>
          <Card>
            <div
              onMouseEnter={() => setIsShown(true)}
              onMouseLeave={() => setIsShown(false)}
            >
            <p>Tele</p>
            {isShown && (
              <div onMouseEnter={() => setIsShown(true)} onMouseLeave={() => setIsShown(false)}>
             <p>Logo</p>
             </div>
             </div>
            )}
          </Card>
       )
    }
    

    Then use it in your Modules component. Now each card manages is own state independently. I only pass the title as a prop because don't now what you need to use inside your card.

    export default function Modules() {
       return (
          <CardWrapper title="title1" />
          <CardWrapper title="title2" />
       )
    }