Home > other >  React add image on mouse hover, smooth transition
React add image on mouse hover, smooth transition

Time:04-22

Problem Description

I am trying to find a way to, whenever a mouse enters a div, for an image to appear gradually, and equivalently, disappear slowly when the mouse leaves.

function App() {
    const imagePath = 'https://via.placeholder.com/100';
    const [showImage, setShowImage] = React.useState(false);

    return (
       <div className="container"
            onm ouseEnter={() => setShowImage(true)}
            onm ouseLeave={() => setShowImage(false)}
            style={ {backgroundImage: showImage ? `url(${imagePath})` : `none` }}>
        
       </div>
    )
}

ReactDOM.render(<App />, document.querySelector("#app"));
.container{
   background-color: orange;
   width: 100px;
   height: 100px;
   animation-duration: 0.75s;
   transition: all 0.5s;
}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
  <div id="app"></div>


What I have tried

  • I tried adding the all prefix to the transition property in css, but that didn't work.
  • I tried looking online for solutions, but I can't seem to find how, and this makes me think that there is a particular way to implement this if it involves an image appearing/disappearing.

Does anyone know how I can solve this problem ?

CodePudding user response:

I just changed div background-image property to add <img> tag inside div and defined transition on tag and default state is false so opacity is 0 (zero) after mouseenter state will true then opacity:1.

I hope below snippet will help you a lot.

function App() {
    const imagePath = 'https://via.placeholder.com/100';
    const [showImage, setShowImage] = React.useState(false);

    return (
        <div className="container"
            onm ouseEnter={() => setShowImage(true)}
            onm ouseLeave={() => setShowImage(false)}>
            <img src={imagePath} alt="hover image" style={{ opacity: showImage ? 1 : 0 }}/>
        </div>
    )
}

ReactDOM.render(<App />, document.querySelector("#app"));
.container{
   background-color: orange;
   width: 100px;
   height: 100px;
   position: relative;
}
.container img{
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
    left: 0;
    top: 0;
    transition: 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<div id="app"></div>

CodePudding user response:

No need javascript here. Just add an img tag, instead of add background on hover, just change it's opacity and css transition will work.

  • Related