Skip to content

change opacity and animated that with react js

i started a simple project with react.in my project i have a paragraph and when mouse hover on paragraph (mouse enter event) a square appears under the paragraph and when hover out from paragraph(mouse leave event) that square disapear.but this occure so fast so i want changing this smoothly and i want use opacity and change that from 0 to 1 and reverse when my events occure.but I do not know what to do to change the opacity with animation in react.

this is my appjs

import './index.css';
import React, {useState} from "react";

function App() {
    const [isShowSquare, setIsShowSquare] = useState(false);
    const showSquare = () => {
        setIsShowSquare(true);
    }
    const hideSquare = () => {
        setIsShowSquare(false);
    }
    return (
        <div>
            <p onMouseEnter={showSquare} onMouseLeave={hideSquare} style={{display:'inline-block'}}>Hover Me</p>

            {isShowSquare ?
                <div className='square'>
                </div>
                : null
            }

        </div>

    );
}

export default App;

and this is my index.css

*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.square{
  width: 50px;
  height: 50px;
  background-color: #61dafb;
}

I would be very grateful if anyone could help me

Answer

Here is a method without using useState though. I don’t know if this part is important, but have a look at my sandbox

First of all you need a css class to define the opacity the method and how much time it will take. Also, your first square class should have opacity: 0, meaning non visible.

When mouse is over text, then you add the extra class to the element.

  const showSquare = () => {
    div.current.classList.add("square-full");
  };

  const hideSquare = () => {
    div.current.classList.remove("square-full");
  };

.square.square-full {
  opacity: 0.5;
  transition: opacity 1s ease-out;
}

.square {
  width: 50px;
  height: 50px;
  background-color: #61dafb;
  opacity: 0;
}

Updated answer: No need for ref

Just use the following code

export default function App() {
  const [ isShown, setShown ] = useState(false)

  return (
    <div>
      <p
        onMouseEnter={() => setShown(true)}
        onMouseLeave={() => setShown(false)}
        style={{ display: "inline-block" }}
        class="paragraph"
      >
        Hover Me
      </p>

      <div className={`square ${isShown ? 'square-full' : ''}`}></div>
    </div>
  );
}

along with the extra class i mentioned before