Using React JSX to set a dynamic color when hovering over an element

Hello there! Thanks for taking the time to read my inquiry.

I have been presented with a challenge involving a specific color chosen by the customer. This color plays a crucial role in the overall application context. I've successfully managed to change the backgroundColor of every relevant item to match the selected { color }. This was achieved quite simply, as shown below:

<div className='navbar' style={{ background: color }}>

Now, I am looking to achieve a similar effect but only when hovering over the items.

I have an initial idea on how this could be accomplished using vanilla JavaScript, however, I am unsure about executing it within a React application. Here's what I have come up with so far:

export default function RecipeList( {recipes} ) {
  const hoverColorItems = document.querySelectorAll('.hoverColor');

  hoverColorItems.forEach((item) => {
     item.addEventListener("onFocus", function() {
        item.style.backgroundColor = { color }
     })
  })

  return (
     <>
         <Link className="hoverColor">Button</Link>
     </>
  )
}

It is important to note that I am aware that the forEach loop and querySelector onFocus method may not function correctly in this scenario. I am simply using them as references to convey my concept more effectively as they are familiar to me.

Thank you for your assistance!

Answer №1

When working with a declarative library like React, it's important not to directly manipulate the DOM. Instead, you should define how the DOM should appear based on the state and then update the state to achieve the desired UI effect.

To handle state changes when a user hovers over or exits an element, you can utilize the onMouseEnter and onMouseLeave events.

A sample code snippet could look something like this:

function App({color}) {
  const [isFocused, setFocus] = useState(false);

  return (
    <Link
      href="https://stackoverflow.com"
      onMouseEnter={() => setFocus(true)}
      onMouseLeave={() => setFocus(false)}
      className="hoverColor"
      style={{
        backgroundColor: isFocused ? color : ""
      }}
    >
      Style using React
    </Link>
  );
}

In the above example, React is instructed on what action to take (set backgroundColor to red) in response to a specific state (isFocused being true). To interact with the DOM, use setFocus.

However, I would suggest utilizing CSS solutions whenever possible. For instance, you can easily achieve hover/focus effects using CSS variables to pass colors from React to CSS.

<Link
  style={{ "--background-color": color }}
  href="https://stackoverflow.com"
  className="link-hover"
>
  Style using CSS
</Link>
.link-hover:hover {
  background-color: var(--background-color);
}

Here is a demo showcasing both approaches: https://codesandbox.io/s/pensive-sun-m9jv2s?file=/src/App.js

(Please note that I simulated the Link component for the demo, your implementation may vary slightly.)

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

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

Why doesn't Select2 function properly in Bootstrap 3 when the tabindex is removed?

There is a bug with Select2 that causes it to malfunction in a Bootstrap 3 modal unless the tabindex element is removed. I have successfully resolved this issue in several modals on my page, but one specific modal still cannot get Select2 to function. Eac ...

Ways to conceal the label without using JavaScript when focusing

I am trying to find a way to hide the label "phone number" when the input is in focus by simply clicking on it. I have attempted using CSS but I need a more effective solution. Please let me know if you can help. <div class="form-row"> ...

Having trouble extracting the responseText from the Ajax request

My current challenge involves making an ajax call and receiving an Object in the response. However, when I attempt to access "responseText," it keeps returning as undefined: var results = API.get('users', { username: un, userpass: pw } ); conso ...

What causes conflicts between CSS and HTML tables?

I'm currently working on designing an email ticket template that incorporates a small table for clients to easily view the subject and description of their ticket. The template was looking great until the table was inserted, causing a complete formatt ...

What is the best way to retrieve the current CSS width of a Vue component within a flexbox layout grid after it has been modified?

There's something about this Vue lifecycle that has me scratching my head. Let me simplify it as best I can. I've got a custom button component whose size is controlled by a flex grid container setup like this: <template> < ...

Nested promises utilized within functional programming techniques

Working on an Angular project involves developing a booking system with various scenarios. The challenge lies in handling different server calls based on the response of a promise, leading to a nested callback structure that contradicts the purpose of prom ...

Using CSS units such as vw, vh, or percentage to specify height is not possible

In my Ionic app, I am adjusting the width and height of a div based on the viewport dimensions. This setup functions correctly on the browser and Android 4.4 devices. However, it does not work as expected on Android 4.2 (the height is constrained to the te ...

Creating a CSS full-width navigation menu

Recently, I came across a menu code on the web that seemed great. However, I wanted to make my menu responsive and full width. Since I am new to CSS and HTML, adjusting the menu code has been a bit of a challenge for me. .menu, .menu ul { list-style: ...

Issue with fuse-box: unable to import ReactDOM

Recently, I decided to switch from webpack to fuse-box for my side project. Everything is compiling without any issues, but when I try to load it, an error pops up: I downloaded a React demo code and it works fine. Additionally, there are no problems wit ...

Adding a JavaScript file in a Ctools modal popup in Drupal: a step-by-step guide

Is there a way to include a JavaScript file in a Ctools modal popup? I tried adding the js file (datatables.js) in the .tpl.php file, but it doesn't seem to be working. The popup isn't recognizing this file. Any suggestions on how to make it wo ...

Is the logo stretching when adding an image in a bootstrap row?

Attempting to utilize Bootstrap 4 for website development, I encountered an issue when adding a logo image and text to the header. The image became stretched, as seen below: https://i.sstatic.net/3qRnE.png Below is the HTML code used: <header> &l ...

How can I effectively utilize executeScript in Selenium and webdriver.io?

I'm currently working on testing a basic form using Selenium, WebDriver.io, and Node.js (with Mocha). Here is a snippet of the code I have: var webdriverio = require('webdriverio'); var expect = require('expect'); describe(' ...

Unable to access the function this.context.getStore in ReactJS Stores due to an error

I currently have the following code: import React from 'react'; import FilterButton from './FilterButton'; import FilterJobsScreen from '../../actions/jobs-screen/FilterJobsScreen'; import JobStore from '../../stores/Jo ...

Turn off horizontal scrolling on your mobile site

I am working on a mobile webpage with a Facebook-like side menu button, but I'm having trouble disabling horizontal scrolling using CSS overflow-x:hidden. Here is the code I have so far: <meta name="viewport" content="width=device-width, initial-s ...

Navigating through nested JSON arrays in JavaScript involves looping through multiple dimensions

I am facing difficulty finding the correct solution to my issue here. I am trying to iterate through the nested Products arrays in order to display each Product name. Can this be achieved with my current code, or should I consider rewriting it to make qu ...

Is it possible to make jQuery dialog text behave like a JavaScript prompt?

Hello there, I have a query! I'm looking to allow users to easily copy text within a dialog window by simply pressing CTRL + C. Is this possible, and if so, how can it be achieved? An instance of this functionality is seen in the javascript alert pr ...

Confirming the data entry format

I am currently utilizing the RobinHerbots/Inputmask plugin to mask telephone input. I am interested in finding out how I can implement input validation to ensure that the user has entered accurate information. Thank you! <form> <input ty ...

Enhance the appearance of rows in a table by adding a captivating marquee effect to those with

I'm working with a table that has 7 rows and 2 tabs for Sunday and Monday. The row corresponding to the current time is highlighted in red. I wanted to know if it's possible to add the following <marquee>My first Row</marquee> effe ...

Having issues passing parameters with Ajax, Python Bottle, Jquery, and JSON collaboration

Every time I make an AJAX request POST, the newUser() function seems to be ignoring any arguments being passed even though I have filled out both userInput and passInput fields. Here's the JS/JQ/AJAX code snippet: var userInput = document ...