I Love ReactJS

Come and see the effect of using React to create an eye-catching and cool hover box.

Preface

this article shows you how to use React and DOM things to achieve a compelling interactive hover box effect. By hovering over the mouse, the box will randomly change the color and display shadows, adding dynamic and visual appeal to the page. Read this article and you'll learn how to use React to implement event handling and dynamic styling, bringing more interesting interactions to your Web application.

scene

in modern Web applications, interactivity and dynamic effects are critical to improving the user experience. Hovering effect is a common way of user interaction, when the user hovers the mouse over a specific area, the relevant elements will change to attract the user's attention. In this article, we will explore how to use React to implement a CSS special effect of a hover square effect.

Let's take a look at →

Development

first, import React and some necessary hook functions, as well as the stylesheet we will use in the component. As follows:

import React, { useEffect, useRef, useState } from 'react'; 
import './index.less'

The code for the

index.less file is as follows:

.App {
  background-color: #111;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  margin: 0;
}

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  max-width: 600px;
  overflow: hidden;
}

.square {
  background-color: #333;
  box-shadow: 0 0 2px #000;
  height: 16px;
  width: 16px;
  margin: 2px;
  transition: 2s ease;
}

.square:hover {
  transition-duration: 0s;
}

then defines an array of colors and a constant SQUARES to set the number of squares. As follows:

const colors = ['#861104', '#7611a0', '#127ec7', '#e2931d', '#2ecc71'];
const SQUARES = 600;

the next step is to create the effect to be implemented as a component and name it HoverBlock . As follows:

/ * *
* hover box effect
* @ constructor
, /
ConstHoverBlock = () => {

  useEffect(() => {
    const container = document.getElementById('container');
    const squares = [];

    for (let i = 0; i < SQUARES; i++) {
      const square = document.createElement('div');
      square.classList.add('square');

      square.addEventListener('mouseover', () => setColor(square));
      square.addEventListener('mouseout', () => removeColor(square));

      squares.push(square);
      container.appendChild(square);
    }

    return () => {
      squares.forEach(square => {
        square.removeEventListener('mouseover', () => setColor(square));
        square.removeEventListener('mouseout', () => removeColor(square));
        container.removeChild(square);
      });
    };
  }, [])

  return (
      <div id="container" className="container"></div>
  )
}

export default HoverBlock;

in the above code, a div element is created using the createElement method, and a square class is added to it. Then, for each square element, mouseover and mouseout event listeners are added to set the square color and remove the color, respectively.

in the return function of useEffect , we remove the event listeners on the square element and remove the square from the container by iterating through the squares array. This ensures that all square elements and related events are cleared when the component is unloaded.

next, refine the two helper functions getRandomColor and setColor used in useEffect to randomly generate colors and style squares.

/ * *
* get random colors
, /
ConstgetRandomColor = () => {
  return colors[Math.floor(Math.random() * colors.length)];
}


/ * *
* set the color
* @ param element
, /
ConstsetColor = (element: any) => {
  const color = getRandomColor();
  element.style.background = color;
  element.style.boxShadow = `0 0 2px ${color}, 0 0 10px ${color}`;
}

in the getRandomColor function, get random color values from the color array by generating a random index.

in the setColor function, first call the getRandomColor function to get a random color, and then apply the color to the background and boxShadow style attributes of the square element, thus realizing the change effect of setting the color and shadow for the square when the mouse is moved.

finally, using the removeColor function to handle the removal of the mouse requires restoring the colors and shadows of the square elements to the default state. As follows:

/ * *
* remove colors
* @ param element
, /
ConstremoveColor = (element: any) => {
  element.style.background = '#333';
  element.style.boxShadow = '0 0 2px #000';
}

at this point, the main code for the component has been written. The next step is to reference the component to the project for use. As follows:

import HoverBlock from "./components/HoverBlock";

function App() {

  return (
    <div className="App">
      <HoverBlock />
    </div>
  )
}

export default App;

start the project and you can see the final effect. As shown in the following figure:

complete code

import React, {useEffect} from 'react';
import './index.less';
const colors = ['#861104', '#7611a0', '#127ec7', '#e2931d', '#2ecc71'];
const SQUARES = 600;


/ * *
* hover box effect
* @ constructor
, /
ConstHoverBlock = () => {

  useEffect(() => {
    const container = document.getElementById('container');
    const squares = [];

    for (let i = 0; i < SQUARES; i++) {
      const square = document.createElement('div');
      square.classList.add('square');

      square.addEventListener('mouseover', () => setColor(square));
      square.addEventListener('mouseout', () => removeColor(square));

      squares.push(square);
      container.appendChild(square);
    }

    return () => {
      squares.forEach(square => {
        square.removeEventListener('mouseover', () => setColor(square));
        square.removeEventListener('mouseout', () => removeColor(square));
        container.removeChild(square);
      });
    };
  }, [])


/ * *
* get random colors
, /
ConstgetRandomColor = () => {
    return colors[Math.floor(Math.random() * colors.length)];
}


/ * *
* set the color
* @ param element
, /
ConstsetColor = (element: any) => {
    const color = getRandomColor();
    element.style.background = color;
    element.style.boxShadow = `0 0 2px ${color}, 0 0 10px ${color}`;
}


/ * *
* remove colors
* @ param element
, /
ConstremoveColor = (element: any) => {
    element.style.background = '#333';
    element.style.boxShadow = '0 0 2px #000';
  }


  return (
      <div id='container' className='container'></div>
  )
}

export default HoverBlock;

so far, we have successfully developed the effect of an interactive hover box by using the Hooks and DOM events of React . When the mouse hovers over the square, the square will randomly change the color and show a shadow effect, thus increasing the interaction and visual appeal of the page.

this hover box effect can be applied to various Web applications, such as display pages, game interfaces, or personal homepages, to provide users with a richer interactive experience.

Finally, I hope you can understand the event handling and dynamic styling methods in React after reading this article, and hope to inspire you to achieve more interesting interactions in future development.

Exit mobile version