Home > Enterprise >  show text on hover (React)
show text on hover (React)

Time:12-07

I have two divs and I want them to show the text on hover, but when I hover over one of them they both show the text. Here is the code:

>     const [text, setText] = useState(0);
>     <div onMouseEnter={e=> setText(1)} onm ouseLeave={e=> setText(0)}>
>         <h1>hover the div to show the text</h1>
>         <p style={{opacity: `${text}`}}>some dummy text</p>
>     </div>
      <div onMouseEnter={e=> setText(1)} onm ouseLeave={e=> setText(0)}>
>         <h1>hover the div to show the text</h1>
>         <p style={{opacity: `${text}`}}>some dummy text</p>
>     </div>

CodePudding user response:

You must set two different useStates for each. In the current situation, when you hover over one of them, your state value becomes one for that one.

Like this:

 const [text, setText] = useState(0);
 <div onMouseEnter={e=> setText(1)} onm ouseLeave={e=> setText(0)}>
     <h1>hover the div to show the text</h1>
     <p style={{opacity: `${text}`}}>some dummy text</p>
 </div>
  <div onMouseEnter={e=> setText2(1)} onm ouseLeave={e=> setText2(0)}>
     <h1>hover the div to show the text</h1>
     <p style={{opacity: `${text2}`}}>some dummy text</p>
 </div>

CodePudding user response:

I have fixed it, here is the code:

 const [text, setText] = useState({firstDiv:0, secondDiv: 0});
 <div onMouseEnter={e=> setText({firstDiv:1, secondDiv: 0})} onm ouseLeave={e=> setText(0)}>
     <h1>hover the div to show the text</h1>
     <p style={{opacity: text.firstDiv}}>some dummy text</p>
 </div>
  <div onMouseEnter={e=> setText({firstDiv:0, secondDiv: 1})} onm ouseLeave={e=> setText(0)}>
     <h1>hover the div to show the text</h1>
     <p style={{opacity: text.secondDiv}}>some dummy text</p>
 </div>
  • Related