Hovering over an image and trying to rotate it results in

Check out my rotating image example on hover in React here

This effect utilizes scale(), rotate(), and transition properties to create an animated rotation when hovering over the parent element. Additionally, overflow: hidden is applied to the parent element to ensure the excess from the image transformation is hidden.

I'm facing an issue where I can see the image but it doesn't rotate when I hover over it in my React implementation. It seems like everything is configured correctly, so what could be missing here?

import React from 'react';
import { Box } from '@mui/material';
import Image from 'mui-image';

const styles = {
    hoverRotate: {
        overflow: 'hidden',
        margin: '8px',
        minWidth: '240px',
        maxWidth: '320px',
        width: '100%',
    },

    'hoverRotate img': {
        transition: 'all 0.3s',
        boxSizing: 'border-box',
        maxWidth: '100%',
    },

    'hoverRotate:hover img': {
        transform: 'scale(1.3) rotate(5deg)',
    },
};

function Rotate() {
    return (
        <Box style={styles.hoverRotate}>
            <Image src="https://picsum.photos/id/669/600/800.jpg" />
        </Box>
    );
}

export { Rotate };

Answer №1

This method of styling does not detect hover events, so it is recommended to use the useState hook to set the hover state of the image (remember to import it using

import { useState } from "react";
)

const [isHover, setIsHover] = useState(false);

To check if the Box element is being hovered over or not, you can use event handlers to update the isHover state accordingly.

<Box
  style={styles.hoverRotate}
  onMouseEnter={() => setIsHover(true)}
  onMouseLeave={() => setIsHover(false)}
>               
  {/* code */}
</Box>

Make sure to move your styles into the Rotate function and apply the key "hoverRotate img" to the appropriate style properties for it to take effect.

const styles = {
  hoverRotate: {
    overflow: "hidden",
    margin: "8px",
    minWidth: "240px",
    maxWidth: "320px",
    width: "100%"
  },

  image: {
    transition: "all 0.3s",
    boxSizing: "border-box",
    maxWidth: "100%",
    transform: isHover && "scale(1.3) rotate(5deg)"
  }
};

Finally, apply the image style to the Image component in your code.

<Image
  src="https://picsum.photos/id/669/600/800.jpg"
  style={styles.image}
/>

For a working example, check out this sandbox: https://codesandbox.io/s/distracted-matan-c43ufb?file=/src/App.js:829-928

Answer №2

Introducing the latest @mui/system styling tool with the new sx prop, simplifying the process by directly passing the styles object:

import React from "react";
import { Box } from "@mui/material";

const boxSx = {
  overflow: "hidden",
  margin: "8px",
  minWidth: "240px",
  maxWidth: "320px",
  width: "100%",

  "& > img": {
    transition: "all 0.3s",
    boxSizing: "border-box",
    maxWidth: "100%"
  },

  "&:hover > img": {
    transform: "scale(1.3) rotate(5deg)"
  }
};

function Rotate() {
  return (
    <Box sx={ boxSx }>
      <img src="https://picsum.photos/id/669/600/800.jpg" />
    </Box>
  );
}

export { Rotate };

If you've been nostalgic for the original @mui/styles (now deprecated) styling method, then you may have been missing out on makeStyles. This involves creating styles and assigning them to the className prop:

import React from "react";
import Box from "@material-ui/core/Box";
import makeStyles from "@material-ui/core/styles/makeStyles";

const useStyles = makeStyles({
  hoverRotate: {
    overflow: "hidden",
    margin: "8px",
    minWidth: "240px",
    maxWidth: "320px",
    width: "100%",

    "& > img": {
      transition: "all 0.3s",
      boxSizing: "border-box",
      maxWidth: "100%"
    },

    "&:hover > img": {
      transform: "scale(1.3) rotate(5deg)"
    }
  }
});

function Rotate() {
  const styles = useStyles();

  return (
    <Box className={ styles.hoverRotate }>
      <img src="https://picsum.photos/id/669/600/888.jpg" />
    </Box>
  );
}

export { Rotate };

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

The BeautifulSoup parsing result differs from the code of the original HTML page

Lately, I've been using BeautifulSoup4 to scrape data from Spotify Charts. It's been working smoothly for a few weeks until today when it suddenly started giving NaN values for all the entries... I suspect that the issue lies in the parsed HTML ...

"Unsuccessful jSON request made by Ajax resulting in undefined response

I've implemented an ajax call to fetch data from a json file and display it in an HTML table. Everything was working fine initially, but now it seems to be returning UNDEFINED. Could it be that the data from the json file hasn't finished loading ...

JavaScript: Locate the HTML Attribute that Matches an ID

If you want to use just JavaScript, without relying on libraries like JQuery, how can you retrieve the data attribute associated with a specific Id? For example: <div id="id-test" data-qa="data-qa-test"> </div> Input: &quo ...

Using http-proxy-middleware in a React application for browser proxy

I'm having trouble with setting up a proxy in my React app. Scenario: I have two React apps, one running on localhost:3000 and the other on localhost:3001. What I want to achieve is that when I click on: <a href="/app2"> <button> ...

Unable to render chart using angularjs-nvd3-directives

After developing a basic Angular - nvd3 project, I decided to utilize liveData.example from the angularjs-nvd3-directives Library on Github. To tailor it for my needs, I made enhancements to integrate with my REST API. Here is the REST API endpoint: http ...

Ensure that only the admin is able to make something vanish for everyone else

Is there a way to hide content for everyone except the admin? Currently, I have this code implemented but it only works when a user is not logged in. When another user logs in, the content is still visible. <?php if( isset($_SESSION['username&a ...

Dynamically adjusting the width of an HTML element with ng-style using percentage values in AngularJS

I am facing a challenge where I need to display a progress bar in my UI based on a percentage value stored in a JSON response object. Here is an example of the JSON object: { completionPercent: 42 } The desired UI outcome should look like this: ┌ ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

Is react-particles-js still compatible for me to integrate?

I recently discovered that the package found here: https://www.npmjs.com/package/react-particles-js has been deprecated. Can I still utilize this package? The codes in question can be viewed at: https://codesandbox.io/s/particle-js-background-forked-woypk ...

The method for retrieving values and $id from a $firebaseArray using angularJS

Hey there, I'm fairly new to working with Firebase and I seem to be stuck on a problem that I can't find a solution for despite looking in many different places. Here is the structure of my Firebase database: I am trying to retrieve data from a s ...

Exploring Protractor testing with Bootstrap modals

I'm having an issue testing a bootstrap modal. Here's the scenario: Click on a button to display the modal The modal body has a list of buttons When I click on one of them, it doesn't do anything My Protractor code snippet: element(by. ...

When trying to use bootbox.confirm within a dynamically loaded AJAX div, the modal unexpectedly opens and

I have implemented bootbox into my project, which was downloaded from . user_update.php is being loaded in a div within users.php using ajax functionality. Within user_update.php, there is a JavaScript function called validateForm(). Right after the functi ...

Using JQuery to make POST requests is successful, however, utilizing the XMLHttpRequest object to make

Currently, I am attempting to make a POST request from Javascript to my server in PHP but without utilizing jQuery. The following code successfully sends the required data to the database: var msg = {}; msg['name'] = 'joe'; msg['m ...

A guide on crafting a test scenario for an AngularJS controller using the Jasmine framework

I recently created an angular module called userModule.js 'use strict'; angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop', ...

Adding the BETA symbol to your Bootstrap navbar is simple and can be done by

Is there a way to include a "BETA" symbol at the top of the "Brand Name" on my Navbar, similar to the "TM" symbol? How can this be achieved? ...

How can I implement changing the page background color based on different routes in ReactJS and React Router?

Is there a way to change the background color of the browser when navigating to a new route in ReactJS and React Router? Check out my tips below that I discovered during my experimentation: I have managed to implement this on individual page views using & ...

What is the best method for saving HTML form data into a Node JS variable?

I am facing an issue with setting the values of HTML form inputs onto my Node JS variables. In the JavaScript code below, I am struggling to assign values to the variables "hostname" and "port," which should then be concatenated to create a new variable ca ...

Using an Ajax XML object to dynamically set images in a DataList

When making an Ajax call to retrieve an XML response and trying to set image names from the XML on a datalist, I encountered some issues. The code snippet I used for setting the image is as follows: $(".Image", tablex).attr('src', product.find( ...

Is there a notification system that sparkles like a precious Facebook gem

Is there a system similar to Facebook's request, message, and notification bubble system that can alert users on their profiles about new messages or notifications? I know Facebook is very advanced, but if anyone knows of something similar, please let ...

Utilizing JSX interpolation for translation in React JS with i18next

I am trying to utilize a JSX object within the interpolation object of the i18next translate method. Here is an example code snippet along with its result: import React from "react"; import {useTranslation} from "react-i18next&qu ...