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

Encountered an issue loading resource: server encountered a status of 500 (Internal Server Error) while working in react framework

Struggling to send a POST request in react using a form, but encountering a 500 error response from the server. The handleSubmit function is designed like this; however, it seems to be ineffective and consistently returns an internal server error with a 50 ...

Toggle the backgroundImage visibility by setting it to either hidden or displayed using jquery

$('.arrow').css("background-image", "url('../img/arrow.png')").hide(); I have implemented a custom solution using CSS and jQuery to hide the downward arrow when scrolling down on my webpage. `$( document ).ready(function() {
 co ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

Exploring a collection of objects housed in a json document

Currently, I'm looking to retrieve a collection of objects using JavaScript from a JSON file that resides on my website. While I could easily embed the array of objects directly into my JavaScript code, I am interested in understanding how to work wit ...

Modifying various states within React using the useState() hook

Curiosity strikes me - what actually happens when I modify more than one state in a handler function? Will they be updated simultaneously, or will the changes occur sequentially? const [x, setX] = useState(0) const [y, setY] = useState(0) const handlerFu ...

Looking for a way to incorporate an image source property into a larger image?

I am working on a function that will enlarge an image when clicked on from a selection of 5 or more available images. The idea is that clicking on a small image will trigger the display of a larger version of that image in a frame. Here is an example of t ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

Exploring the colors of legend navigation icons in Google Pie charts

Is there a way to customize the color of the navigation links in Google pie charts (specifically the blue text in the bottom right corner)? ...

Determine the Size of an Image File on Internet Explorer

Is there an alternative method? How can I retrieve file size without relying on ActiveX in JavaScript? I have implemented an image uploading feature with a maximum limit of 1 GB in my script. To determine the size of the uploaded image file using Java ...

React / NextJS: Repeating Audiowave Component

I am currently developing a chat application in NextJS that includes text-to-speech functionality. To visualize the audio playback waveform, I have integrated a third-party library called wavesurfer.js Though the audio implementation is functioning proper ...

The error message "require is not defined in React.js" indicates that the required dependency is

As I delve into React coding, the following lines are a part of my code: var React = require('react'); For setting up React, I referred to tutorialspoint. The installation directory is set to /Desktop/reactApp/. My React code is executed from ...

When using threejs, the color set for setClearColor is supposed to be white. However, when calling an external HTML file, it unexpectedly renders as

When I call an external HTML file in Three.js, the value for setClearColor is white but it renders as black. How can I solve this issue? Click here to view the image Here are the codes from the external file: <div id="3d-modal"></div> <sc ...

Creating a hierarchical JSON layout for constructing dual d3.js graphs side by side

I am currently struggling with navigating through a JSON structure that I created in order to generate side-by-side donut charts. I suspect that my structure is not ideal and would greatly appreciate any guidance. My inspiration comes from Mike Bostock&ap ...

Error: Unable to display React modal

I have implemented a reusable confirm dialog in React. Here is the code: import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Box, IconButton, Typography, } from '@material-ui/core'; import { Close } from "@material-ui/icons&q ...

Tips on transmitting and receiving substantial JSON information

As a newbie in the full-stack development world, I am currently on a quest to find an efficient method for transmitting and retrieving large data between my React front-end and Express back-end while keeping memory usage to a minimum. My project involves b ...

Connecting components in React using their IDs on the same page

In my project to create a one-page website in React, I have divided it into different components such as a navbar component and an education component. My goal now is to link the navbar to the education section. In my App.js file, I am including the educat ...

How to Apply a CSS Class to the Body Tag in Angular 2.x

How can I add [class.fixed]="isFixed" to the body tag when Angular 2.x is bootstrapped inside the body (outside my-app)? <html> <head> </head> <body [class.fixed]="isFixed"> <my-app>Loading...</my-app> </body> & ...

Error encountered: Unexpected syntax error found in jQuery ajax call

I am attempting to send a simple request to Instagram using the code snippet below: $.getJSON("https://www.instagram.com/kidsfromthe90sband/media/?callback=?", function(data) { alert(JSON.stringify(data)); }); http://jsfiddle.net/FPhcr/731/ ...

Fresh sheet with a view through the window

I need to print a table and two popup windows when an action is triggered, but I am facing issues with the page-break in CSS. None of the solutions I have attempted so far seem to work. Currently, the two pop-up windows overlap with the table data, and I w ...

Error: The route cannot be established within an asynchronous function

The following code snippet is from the api.js module, responsible for creating a test route: 'use strict'; module.exports = function (app) { console.log("before route creation"); app.get("/api/test", (req, res) => { ...