Is there a way to apply the style property only when a component is hovered in Next.js?

I would like the ability to hover over a component and have it display with unique CSS characteristics. For instance, if I hover on item A, I only want item A to stand out from the rest.

Currently, I am using this method of changing the element's background image, here is my code:


const StatsIndicators = () => {

    const someArray = ['10%', '50%', '60%', '60%']

    const [isHovering, setIsHovering] = useState(false)
    const [hoverStyle, setHoverStyle] = useState({})
    const [index, setIndex] = useState(0)

    const mouseEntered = (index) => {
        setIsHovering(true);
        setIndex(index + 1);
    }
    const mouseLeft = () => setIsHovering(false)


    useEffect(() => {
        if (isHovering) {
            setHoverStyle({
                background: `center url("/images/stats/rounded-images/${index}.png") no-repeat`,
                border: '1px solid #f5f5f5',
                boxShadow: '0px 0px 10px #f5f5f5',
                transition: 'all 0.3s ease-in-out'
            });
        } else {
            setHoverStyle({});
        }
    }, [isHovering]);

    return (
        <>

            {<Grid container className={style.test}>
                {
                    someArray.map((item, index) => (
                        <Grid item xs={12} md={3} key={index}>
                            <div className={style.statsContainer}>
                                <div className={style.circle} style={hoverStyle} onMouseEnter={(e) => { mouseEntered(index) }} onMouseLeave={mouseLeft}>
                                    <p className={style.circleStats}>Some value</p>
                                    <p className={`${style.circleStats} ${style.circleStatsDescription}`}>Ver más</p>
                                </div>
                                <p className={style.indicator}>Some name</p>
                            </div>
                        </Grid>
                    ))
                }
            </Grid>}
        </>
    )
}

Upon hovering over an item in the map, I get the following result:

I want to avoid displaying the background image on the other circles, but I'm unsure how to display it only on the hovered one. I thought about comparing the index of the hovered item and only displaying the background if that one is active...but I can't decide on the best way to implement this.

Answer №1

Currently, the styles are being applied to all circles when one of them is hovered. The correct approach would be to conditionally apply the styles based on the active hovered circle (using a unique property such as an id).

Live Code Demo:

https://codesandbox.io/s/fervent-wildflower-tc1xiy?fontsize=14&hidenavigation=1&theme=dark

See Working Demo

Code Snippet:

import { useState } from "react";
import "./styles.css";

const data = [
  {
    id: 1,
    url: "https://images.dog.ceo/breeds/terrier-american/n02093428_3305.jpg"
  },
  // additional data items...
];

export default function App() {
  const [activeId, setActiveId] = useState(0);

  const setActiveElementOnHover = (id) => {
    setActiveId(id);
  };

  const resetActiveElementOnLeave = () => {
    setActiveId(0);
  };

  return (
    <div className="app">
      <h1 className="headline">Dog Gallery</h1>
      <div className="gallery-container">
        {data.map(({ id, url }) => (
          <div
            key={id}
            role="presentation"
            className="circle"
            style={{
              background:
                activeId === id ? `center / cover no-repeat url(${url})` : ""
            }}
            onMouseEnter={() => setActiveElementOnHover(id)}
            onMouseLeave={resetActiveElementOnLeave}
          >
            <p>Dog #{id}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

CSS Styles:

.app {
  font-family: sans-serif;
  text-align: center;
}

.gallery-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 800px;
  margin: 0 auto;
}

.circle {
  padding: 75px;
  border-radius: 50%;
  background: navy;
  color: white;
  margin: 0 10px;
}

.headline {
  font-size: 10rem;
  color: navy;
}

p {
  padding: 0;
  margin: 0;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disabling the camera feed in a React application

Attempting to turn off the webcam using javaScript in React has been a bit challenging. Whenever I shift to a new component or when a component is destroyed, my react component immediately moves to the next page, but the webcam light remains on in the new ...

How to eliminate all <style> tags across the board using Regex in JavaScript

Is there a way to utilize regex in JavaScript for removing all instances of <style>, <style type="text/css">, </style>, and <style type="text/css"/>? I want the outcome to only present the CSS without any style tags. The code below ...

I am looking to retrieve the values entered in a textbox from an HTML document and then post them using a JSON file in Node.js when the submit button is

Here is the JavaScript code I have written: $(document).ready(function(){ $('form').on('submit', function(){ var email = $("form input[type=text][name=emails]").val(); var todo = {email: email.val(), ...

Updating state based on input from a different component

I am attempting to modify the state of the page index in index.js from the Pagination component, Here is my index.js code: import useSWR from 'swr'; import { useState } from 'react'; const Index = ({ data }) => { const ini ...

Having trouble getting req.files to work in a Node.js Express application?

Hello there, I'm facing an issue with accepting an uploaded file. Every time I call req.files, it comes out as undefined. I can't seem to figure out what I am doing wrong... Below is a snippet of my app.js file: var express = require('expr ...

Error encountered in Vue3: An uncaught TypeError occurred when attempting to "set" a property called 'NewTodo' on a proxy object, as the trap function returned a falsish

I encountered an error message: Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'NewTodo' This error occurs when attempting to reset the input text value within a child component (FormAddTodo.vue). App.vue: expo ...

Tips for including an option in multiple groups using MUI Autocomplete

My application has users who can belong to multiple groups as defined by the backend system. For instance, User 1 may be in groups 1 and 2, while User 2 could be a member of groups 2 and 3. What I want is for my Autocomplete groups to be displayed like th ...

Error in the Angular-UI calendar

I'm encountering an issue while trying to set up the angular-ui calendar. When I run it, I get the following error: TypeError: undefined is not a function at Object.eventsWatcher.onChanged (http://localhost/fisioGest/js/calendar.js:262:41) Despite b ...

JavaScript appending checkboxes to a list not functioning as expected

I have not been using jQuery, JavaScript, and HTML to create a list of products. The task I am working on now is the ability to select multiple items from this list. Currently, the HTML list is dynamically populated with <li> elements using JavaScri ...

Switching background images for DIVs when links are rolled over

Having trouble changing the background image of a div when a user hovers over a link. Any ideas on what might be causing this issue? <style> #divToSwap { background-image: url(black.jpg); height: 150px; width: 150px; } </style> &l ...

Can you explain what is meant by an "out of DOM" element?

I'm feeling a bit lost when it comes to DOM nodes and all the terminology surrounding them. Initially, I believed that the DOM consisted solely of what I could see in my inspector - nothing more, nothing less. However, I've come across functions ...

"Configuring next-images using an existing next.config.js file: A step-by-step guide

I am looking to integrate the npm package next-images into my nextjs application. Upon reviewing the documentation for next-images, it advises creating a next.config.js file with the following code snippet: const withImages = require('next-images&apo ...

unable to send array in cookie through express isn't functioning

Currently, I am in the midst of a project that requires me to provide the user with an array. To achieve this, I have been attempting to utilize the res.cookie() function. However, each time I try to pass an array as cookie data, the browser interprets it ...

Ways to create a vertical bottom-up tree view using d3.js

I am trying to create a reverse tree view, starting from the bottom and moving up. What modifications do I need to make? Here is the link to my JS Fiddle: ...

Implementing Content Security Policy (CSP) for Nextjs and Django Integration

When working on a project utilizing Nextjs for the frontend and Django for the backend API, where is the ideal location to define the Content Security Policy (CSP)? I've come across examples suggesting that CSP rules can be specified in the next confi ...

Modifying the state object in ReactJS: A step-by-step guide on updating values

Below my query and explanation, you will find all the code. I am currently attempting to update the state in a grandparent class. This is necessary due to file-related reasons, and I am using Material-UI for text boxes. Additionally, I am implementing Red ...

Leverage the power of openCv.js within your next.js projects

I am attempting to incorporate openCv.js into my next.js application a. I started the project with: npx create-next-app b. Next, I installed: $ yarn add @techstark/opencv-js c. Imported OpenCV with: import cv from "@techstark/opencv-js" d. Ho ...

Deleting an element from a JavaScript array

I have a collection of javascript functions that manage intervals by setting and clearing them. The intervals are stored in an array called intervals[]. config: { settings: { timezone: 'Australia/Perth,', base_url: location.p ...

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...