Utilize a viewpoint alteration alongside a floating effect on a specific element

I thought this would be an easy task, but I seem to be missing something as it doesn't work for me.

The goal is to use the perspective() and rotateY() functions in a transform to create a perspective effect on an element. Additionally, there should be a transition that updates the transform attribute's value on hover, changing the rotateY() value to negative for a mirroring effect from left to right. You can find the working code on Codepen here. I am implementing this in React.

My App.tsx that isn't functioning properly

I have defined all styles and applied them inline.

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

const styles = {
    imageCard: {
        display: 'inline-block',
        boxSizing: 'border-box',
        margin: '1rem',
        width: '240px',
        height: '320px',
        padding: '8px',
        borderRadius: '1rem',
        background: 'url(https://picsum.photos/id/1049/240/320)',
        boxShadow: 'rgba(0, 0, 0, 0.25) 0px 25px 50px -12px',
    },

    perspectiveLeft: {
        transform: 'perspective(1500px) rotateY(15deg)',
        transition: 'transform 1s ease 0s',
    },

    'perspectiveLeft:hover': {
        transform: 'perspective(3000px) rotateY(5deg)',
    },

    perspectiveRight: {
        transform: 'perspective(1500px) rotateY(-15deg)',
        transition: 'transform 1s ease 0s',
    },

    'perspectiveRight:hover': {
        transform: 'perspective(3000px) rotateY(-5deg)',
    },
};

function Perspective() {
    return (
        <Box styles={styles.imageCard}>
            <Box style={styles.perspectiveLeft}></Box>
            <Box style={styles.perspectiveRight}></Box>
        </Box>
    );
}

export { Perspective };


Answer №1

There are various techniques to implement these styles in React, however, using inline styles is not recommended as you cannot manipulate the :hover styles with inline styles.

An alternative approach is to utilize CSS classes similar to how it's done in your code pen. The only adjustment needed for React is changing class=... to className=...:

import "./styles.css";

export default function App() {
  return (
    <div className="card-container">
      <div className="image-card perspective-left"></div>
      <div className="image-card perspective-right"></div>
    </div>
  );
}

https://codesandbox.io/s/perspective-cards-using-css-classes-k13spv?fontsize=14&hidenavigation=1&theme=dark


Considering that you were exploring MUI's Box, I assume you may want to integrate this into a project with MUI and potentially prefer using CSS-in-JS methods rather than global CSS class names. Below is an example using MUI's styled API. This would have a similar appearance if implemented using Emotion's styled API which is utilized by MUI's implementation:

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

const ImageCard = styled("div")`
  display: inline-block;
  box-sizing: border-box;
  margin: 1rem;
  width: 240px;
  height: 320px;
  padding: 8px;
  border-radius: 1rem;
  background: url("https://picsum.photos/id/1049/240/320");
  box-shadow: rgba(0, 0, 0, 0.25) 0px 25px 50px -12px;
`;

const ImageCardLeft = styled(ImageCard)`
  transform: perspective(1500px) rotateY(15deg);
  transition: transform 1s ease 0s;

  &:hover {
    transform: perspective(3000px) rotateY(5deg);
  }
`;

const ImageCardRight = styled(ImageCard)`
  transform: perspective(1500px) rotateY(-15deg);
  transition: transform 1s ease 0s;

  &:hover {
    transform: perspective(3000px) rotateY(-5deg);
  }
`;

export default function Perspective() {
  return (
    <div>
      <ImageCardLeft />
      <ImageCardRight />
    </div>
  );
}

https://codesandbox.io/s/perspective-cards-gce895?fontsize=14&hidenavigation=1&theme=dark

Answer №2

Implement this cool animation

npm install react-parallax-tilt

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

What steps need to be taken to set up Node.js to accommodate requests from external sources beyond just localhost?

After creating an application using NextJs, I successfully built it and ran it on a node server by executing 'npm run start' in Powershell. Everything works perfectly when accessing it locally through port 80. However, my Windows Server 2019 does ...

Modify the page's query parameters by incorporating an input field within NextJS's App Router

I'm trying to update query parameters based on user input dynamically using the onChange event. However, I'm facing an issue where the query parameters are updated before the input value is updated after a slight delay. My aim is to achieve insta ...

Pagination Bug: Index Incorrectly Grabbed Upon Navigating to Next Pages

I encountered an issue with my paginated article list (105 articles with 10 per page). Everything works fine on the first page, but when I click on an article from page 2 onwards, it takes me to the index of the very first article in the array. <div cla ...

Ensuring the clickable area of the button aligns perfectly with the button itself and adjusting the arrow position to be

Check out the sandbox here: https://codesandbox.io/s/vigilant-currying-h7c3r?file=/styles.css If you are looking for the classes .line and .arrow, they are what you need. When you create an event, notice how the arrows appear too low, with the clickable a ...

Can responsive images be utilized with a DIV's background-image property?

For my website, I want to incorporate a variety of Thumbnails that are retrieved from a database and displayed in different sizes within a Masonry grid. Typically, I would use background-image:url(image.jpg); background-size: 100% 100%:, but I am aiming t ...

Achieving a fixed position within a div using CSS

Is there a way to arrange elements inside a div without modifying the HTML code? Yes, CSS can help you achieve this. Consider these blog posts: The issue at hand is that the 'Read more' button gets pushed down when the title or content of the p ...

Change the syntax to use async-await

Is it worth converting the syntax to async-await and how can I achieve this? // ---- UserRoutes ---- router.get('/user', middlewareJwt.jwtHandler, function (req, res) { UserService.get(req.userId, (user) => successCbk(res, 200, { ...

Storing Selenium WebElement in memory for extended periods to retrieve its details: A guide in C#

I am using Selenium and C# to monitor a website for any new items that may appear. The website contains a list of <div class="myClass"> elements displayed in a table format with multiple sub-divs. Periodically, I scan all the displayed divs to check ...

Building a table using jQuery and adding elements using JavaScript's append method

Greetings! I've been attempting to add new records from a form that registers or updates student information, but unfortunately it doesn't seem to be functioning correctly. Can anyone point me in the right direction as to why this may be happenin ...

How to verify in HTML with Angular whether a variable is undefined

When it comes to the book's ISBN, there are instances where it may not be defined. In those cases, a placeholder image will be loaded. src="http://covers.openlibrary.org/b/isbn/{{book.isbn[0]}}-L.jpg?default=false" ...

In the realm of HTML Canvas, polygons intricately intertwine with one another

Currently, I am attempting to create multiple polygons from a large JSON file. Instead of being separate, the polygons seem to be connected in some way. The project is being developed in next.js. Below are the relevant code snippets: Canvas.tsx // ../co ...

Shade within the autocomplete

Is there a way to make the color property warning work on my autocomplete element at all times, rather than just on focus? Any suggestions or workarounds? Check out this code sandbox for reference. I really want the warning color to be visible constantly ...

Highlight particular terms (key phrases) within text contained in a <td> tag

I am currently working on a project and facing a challenge that I am unfamiliar with. My task is to highlight specific keywords within text located inside a <td> element. I cannot manually highlight the keywords as the texts are dynamic, originating ...

Tips for removing duplicate objects from an array

I am utilizing the underscore.js plugin in my code I experimented with it on jsfiddle var basket=[{ "basketitems":[{"items":[]}], "itemdetails":[{ "amountPledged": "100", "bActivity": "Handloom Wo ...

Error encountered: "Jest error - TypeError: Unable to access property 'preventDefault' because it is undefined."

I encountered an issue while testing the function below, resulting in the error mentioned above. function toggleRecovery = e => { e.preventDefault() this.setState( { recovery: !this.state.recovery }, () => { ...

Adjust the text placement on the toggle switch to turn it On or Off

I am looking to create a toggle switch with a small size. I found some code on Stack Overflow that I tried but it didn't work as expected. The code snippet I attempted to use is from another helpful post. My goal is to have the "on" text align to th ...

Is there a way to identify the specific button that was clicked within an Angular Material dialog?

import {Component, Inject} from '@angular/core'; import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material'; /** * @title Dialog Overview Example with Angular Material */ @Component({ selector: 'dialog-overview-ex ...

Leveraging route configuration's scope in HTML

As a beginner in AngularJs, I am currently exploring the creation of a single page application. However, I am encountering difficulties in converting my initial code into more professional and efficient code. During this conversion process, I have separate ...

Tips for structuring a SQL query result in an AngularJS application

Forgive me if this code is not up to par with the best standards, as I am still relatively new to angular.js. The issue I am facing is that when the data is returned from my query, it appears as a block of text. Despite using echo statements in search.php ...

Adjust the scroll position when the height of a div is modified

Imagine we have a large div A with a height value and below it are other divs B, C, and more. If the user is viewing divs B or C, and A reduces its height by half, the scrolling position will remain the same. However, divs B and C will move up by that amo ...