Ways to change the background image when hovering in a React component

I'm having trouble trying to scale my background image by 1.5 when the user's mouse enters. Here is the code I have so far:

import React from 'react';
import Slider from './index';
import horizontalCss from './css/horizontal.scss';
import content from './content';
import SourceView from './SourceView';
import './css/styles.scss';

function Autoplay() {
return (
<div>

<Slider classNames={horizontalCss} autoplay={3000}>
{content.map((item, index) => (
<div
key={index}

style={{ background: `url('${item.image}') no-repeat center center`, 
                           '&:hover': {
background: 'white',
transform: 'scale(1.5)',
}, }}
>
<div className="center">
<div className="textWrapper">
<h2>{item.title}</h2>
</div>
</div>
</div>
))}
</Slider>

</div>
);
}

export default Autoplay;

What adjustments should I make to get this working properly?

Answer №1

It has been noted by several individuals that the issue lies not with React, but with the style property in HTML lacking support for CSS selectors like :hover. It should also be mentioned that &:hover is not considered valid CSS, but rather valid SCSS when preprocessed by your chosen webpacker.

The styles specific to hovering on your <div> element do not react as intended, so they could easily be placed within a class instead.

.my-image-class {
  background-repeat: no-repeat;
  background-position: center;

  &:hover {
    background: white;
    transform: scale(1.5);
  }
}

You can then switch the background image when not hovering using:

<div
  key={index}
  className="my-image-class"
  style={{ background: `url('${item.image}') }} 
>

For added sophistication, consider making your hover image reactive. The approach outlined above may prove inadequate. Check out Kalabasa's answer which leverages dynamic CSS variables (MDN docs) for responsive class properties.

You would define your backgrounds in the class like this:

.my-image-class {
  background-image: var(--my-image);
  background-repeat: no-repeat;
  background-position: center;

  &:hover {
    background-image: var(--hover-image);
    transform: scale(1.5);
  }
}

Then update the variables dynamically:

<div
  key={index}
  className="my-image-class"
  style={{ '--my-image': `url(path)`; '--hover-image': `url(other-path)` }} 
>

Answer №2

When using Inline Style, keep in mind that it doesn't accommodate pseudo selectors. It is recommended to transfer your hover style css to your styles.scss file and opt for using a className or id instead.

Answer №3

Are you searching for a similar effect? Check out this Demo on stackblitz. It enlarges the block when hovered over. If Stackblitz is not accessible, here is the code snippet:

styling :

html, body, #app {
  margin: 0;
  padding: 0;
  position: relative;
}
.app-component{
  position: absolute;
  width: 300px;
  height: 200px;
  background-image: url('https://picsum.photos/200/300');
  background-size: cover;
  border: 1px solid black;
  top:100px;
  left:100px;
}

.app-component:hover{
  transform: scale(1.5);
  transition:transform 1s linear;
}

app structure:

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

const App = () => {
    return (
      <div className="app-component">
      </div>
    );
}

render(<App />, document.getElementById('root'));

It's recommended to handle this in your CSS rather than using inline styles whenever possible.

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

How to supersede a random class in Material-UI with JSS

Trying to customize the style of a material textField by using a JSS selector that can target a dynamically generated classname. The custom style code snippet would be something like this: const styles = { '@media (min-width: 768px)': { ...

Arrange two input fields side by side if the quantity of input fields is unspecified

I am currently in the process of developing a project using Angular. I have implemented an *ngFor loop to dynamically add input fields based on the data retrieved from the backend. Is there a way I can ensure that two input fields are displayed on the same ...

What could be causing my Font Awesome icon background to fail to load?

As a newcomer to website design, I am currently learning CSS. I seem to be facing an issue where the background for the first two icons has loaded successfully, but the second one isn't displaying. .bg-instagram { padding: 7px 10px; border-radi ...

Initiate a series of tasks and await their completion using RxJS / Redux Observables

My app requires an initialisation action to be fired, followed by a series of other actions before triggering another action. I found a similar question on Stack Overflow However, when attempting this approach, only the initial APP_INIT action is executed ...

The @media print rule for Angular 16 in the style.css file is not functioning properly

I'm currently working on an Angular component called ViewTask, which has a template that is rendered inside the app component. The app component also consists of a side nav bar. My goal is to only display the content inside the 'print-section&apo ...

The ng-model binding does not automatically update another ng-model within the same object

Check out this code snippet: http://plnkr.co/edit/aycnNVoD96UMbsC7rFmg?p=preview <div data-ng-app="" data-ng-init="names=['One']"> <input type="text" ng-model="names[0]"> <p>Using ng-repeat to loop:</p> <ul> ...

What is the reason that when the allowfullscreen attribute of an iframe is set, it doesn't appear to be retained?

Within my code, I am configuring the allowfullscreen attribute for an iframe enclosed in SkyLight, which is a npm module designed for modal views in react.js <SkyLight dialogStyles={myBigGreenDialog} hideOnOverlayClicked ref="simpleDialog"> <if ...

Having difficulty adding a custom library from a repository into an Ember project as a dependency

I've been working on a WebGL library that I want to include as a dependency in an EmberJS project. It seems like I should be able to do this directly from the repository without creating an npm package, but I'm running into some issues. To illus ...

Tips for saving data in the $localStorage as an object

I need to store all the items in $localStorage like this: $localStorage.userData.currentUser = data.name; $localStorage.userData.devId= data.id; $localStorage.userData.userRole = data.roles[0].name; $localStorage.userData.userId = data.user_id; Here is t ...

Displaying a PDF in a React application using content stored on IP

I'm having trouble displaying a PDF file that is stored on IPFS in React using the React PDF package. Here is my code: <div> <Document file={"https://ipfs.io/ipfs/" + this.state.IPFSlink} onLoadSuccess={this.onDocumentLoadSuccess} ...

Is there a way to modify my function expression without using any state variables?

Currently working on a jQuery game where the player is generated upon clicking a button. Below is the function expression I'm using to store the player's information: var getPlayerData = function() { return { name: $("#name").val(),/ ...

Using sinon.js version 1.10, jQuery version 2.1, and making synchronous requests

I have been attempting to simulate a server using sinon.js and calling it with jQuery.ajax, but I am facing issues getting it to work. Here is the code snippet: $(function() { var server = sinon.fakeServer.create(); server.respondWith('POST&apo ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

In a React class, where is the best place to add a conditional statement?

I need to incorporate a conditional statement that will display a certain percentage value in green if it is positive, and red if it is negative. However, I am uncertain about the placement of this conditional statement. <div> {this.state.tableData.m ...

Failure to trigger jQuery.ajax success function on Windows XP operating system

Snippet: $.ajax({ type: "POST", url: "students/login", data:{"data[Student][email]":_email,"data[Student][password]":_password}, beforeSend: function(){ $("#confirm").text(""); }, error: function (xhr, status) { ale ...

The Discord Bot is displaying an error message labeled as "DiscordAPIError[50035]"

Here is the code in my ticket_system.js file: const { Client, MessageEmbed, MessageActionRow, MessageButton, Modal, TextInputComponent, } = require("discord.js"); const settings = require("./settings"); ...

what's the reason for ajax constantly sending requests back-to-back?

Today, I find myself pondering. In my current project, the ajax calls are not behaving asynchronously. Each request is being sent one after the other. As one request is being processed, all other requests are getting stuck in a pending state. You can ob ...

Using a video as a background in HTML

My code has an issue where I have set overflow: hidden in the CSS but the video is still not displaying below the text as intended. The relevant CSS snippets are: fullscreen-bg { top: 0; right: 0; bottom: 0; left: 0; overflow:hidden ...

Vertical stability bar

I need help creating a vertically fixed navigation bar for my website. Currently, I am using a method that has been discussed in various posts: HTML: <html> <head> src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">< ...

Tips for adding a CSS class to an HTML element on-the-fly

As a newcomer to JavaScript and AngularJS, my question may be considered naive by some. I am currently working on a tutorial project involving AngularJS. Here is the HTML code snippet I am dealing with: <link href="http://netdna.bootstrapcdn.com/boo ...