Animations and transitions for cards

import Section from '@/components/section'
import {Card, CardHeader, CardBody, CardFooter, Divider, Link, Image, Button} from "@nextui-org/react";
import { CSSProperties, useState } from 'react';
 
const Index = () => {
  const ExpandedCard = ({ card }: { card: { name: string; price: string } }) => {
    return (
      <div
        style={{
          width: '100%',
          height: '30vh',
          backgroundColor: 'white',
          padding: '20px',
          borderRadius: '10px',
          boxShadow: '0px 0px 10px rgba(0, 0, 0, 0.2)',
          transition: 'opacity 0.5s ease-in-out', // Add transition effect
        }}
      >
        <h2>{card.name}</h2>
        <p>{card.price} RSD</p>
        <button onClick={() => setExpandedCard(null)}>Close</button>
      </div>
    );
  };
 
  const [expandedCard, setExpandedCard] = useState<number | null>(null);
 
  const handleCardClick = (index: number) => {
    setExpandedCard(index);
  };
 
  const cards = [
    { name: 'Tost', price: '140' },
    { name: 'Sendvic', price: '150' },
    { name: 'Sendvic', price: '150' },
    { name: 'Sendvic', price: '150' },
    { name: 'Sendvic', price: '150' },
    { name: 'Sendvic', price: '150' },
    { name: 'Sendvic', price: '150' },
    { name: 'Sendvic', price: '150' },
  ];
 
  return (
    <Page>
      <Section>
        {expandedCard !== null ? (
          <ExpandedCard card={cards[expandedCard]} />
        ) : (
          <div className="grid grid-cols-2 gap-2 justify-center">
            {cards.map((card: { name: string; price: string }, index: number) => (
              <Card
                key={index}
                isPressable
                onClick={() => handleCardClick(index)}
                style={{
                  transition: 'opacity 0.5s ease-in-out', // Add transition effect
                }}
              >
                <CardBody>
                  <img src="https://via.placeholder.com/200x150" alt="Placeholder Image" />
                  <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                  }}>
                    <h5>{card.name}</h5>
                    <p>{card.price} RSD</p>
                  </div>
                </CardBody>
              </Card>
            ))}
          </div>
        )}
      </Section>
    </Page>
  );
};
 
export default Index
 

I'm experiencing issues with the animations in my NextJS project. As a beginner, I'm not sure what's causing the problem.

I'm using NextUI for the UI components, but it doesn't seem to be helping resolve the animation issue.

The cards on my page appear and disappear without any animation effects.

I suspect that the lack of synchronization between expanded cards and clicked cards may be preventing the CSS animations from functioning properly.

Answer №1

While I may not be a React pro, it's clear that from a CSS perspective, the current setup won't cut it. Your browser is unable to smoothly transition between the two cards since it lacks the necessary information: You're currently displaying one card, and when it needs to expand, you simply show another expanded card. However, for a transition to be successful, it needs to occur within the same element transitioning from state A to state B. Therefore, I recommend reevaluating your approach. How exactly should the image appear? Should it slide in from the left or fade in using opacity?

Start by creating two distinct CSS classes representing the separate states of the card, then apply transitions to the desired properties. Keep in mind that computed properties cannot be transitioned. For example, without clearly defining height values for both states, transitioning the height of the card will not work as intended.

I hope this guidance proves useful. Feel free to reach out if you require further assistance!

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

Is there a way to incorporate content onto a webpage solely through the use of CSS and JavaScript?

Currently, I am in the process of developing a real estate website that utilizes a paid service for displaying real estate listings. The unique aspect of this setup is that my website operates as a subdomain of the main listings website, resulting in a URL ...

Define two categories within the Attributes interface

To avoid theme-ui errors in the sx prop, I need to declare both of these statements: declare module "react" { interface Attributes { sx?: ThemeUIStyleObject; } } and declare module "react" { interface Attributes { sx?: Sx ...

Looking to display lists of over 100,000 items simultaneously in a React application

Our current challenge lies in rendering the entire list at once, causing a lag in the browser performance. We are aiming to display a chart with over 100k items in an array, all of which need to be shown on the chart. Does anyone have suggestions for opt ...

I am experiencing issues with the visibility of my background on certain mobile browsers

Apologies for repeating a similar question, but I've already tried the solutions mentioned in other posts. On my webpage, I have a table with a background image set using CSS. html { width:100% height: 100%; margin: 0px; padding: 0px; border: none; } ...

Surprising use of template string value

After following a tutorial, I decided to create ProductScreen.js and Product.js. However, when implementing my code, I encountered some warnings. Can anyone help me identify the issue? product.js import React from 'react' import Rating from &apo ...

What are some effective strategies for incorporating design patterns into my Bookstore project?

I am a full-stack developer and currently pursuing my software engineering degree in the second year of university. I am currently working on a Bookstore project using Spring Boot for the backend and React for the frontend. As part of this project, I nee ...

Retrieving rich text field content from Contentful

I am currently in the process of creating a blog section for my personal website, and after exploring various options, I have decided to go with Contentful as my headless CMS. While I have managed to successfully access certain fields using the following q ...

Is it possible to apply identical css styles to multiple ids at once?

Is there a way to accomplish this? .apple, .orange, .kiwi h1 {color: #892828;} I'm having trouble making it work. Any suggestions? ...

Encountering an issue with TypeScript error code TS2322 when trying to assign a className to the @

Encountering a typescript error when trying to apply a className to a Box element. Interestingly, the same code works on other developers' machines with almost identical configurations. Current dependencies: "@material-ui/core": "4.11. ...

JavaScript Equivalent of jQuery's removeClass and addClass Functions

I am faced with the challenge of rewriting the following code without using jQuery: document.querySelector('.loading-overlay').classList.remove('hidden'); Can anyone provide guidance on how this can be achieved? ...

How can I show an array object in a map when clicked to open a modal?

I recently started working with React and NextJS. In my project, I have an array containing role objects that I need to display on the page along with their descriptions. My goal is to show specific properties of each object when a user clicks on the respe ...

Embed an external website within a div element

Is there a way to embed an entire external website onto another site, without scroll bars or borders? I attempted this method but the entire page did not load, and there were still scroll bars and borders present. <!DOCTYPE HTML> <html> <b ...

Creating a unique custom theme for Twitter Bootstrap at 1200px and 980px screen sizes

Using the Twitter Bootstrap CSS framework, I have successfully created a custom navigation bar for desktop devices with a width of 1200 pixels and above. Now, I want to create similar navigation bars for other screen widths such as 980px, tablets, and phon ...

Challenges with file types in the build directory of a React Express application

My website was running smoothly until yesterday, but now I am encountering some issues. It is a React app built with Express and NodeJS. While the website works fine in development mode using yarn start, I am facing errors in production: GET https://www.m ...

Is there a way to horizontally align my navigation bar links with CSS while maintaining grey borders on the sides?

What is the best way to center my navigation bar links using CSS without losing the grey sides? Both Blogs and History have dropdown menus. Check out this screenshot: https://i.sstatic.net/2kvTm.png (source: gyazo.com) CSS: .navbar ul { list-styl ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

Showcasing or concealing.JSON data depending on the selected item in a React and MaterialUI application

Looking to enhance the user experience, I am developing a dynamic FAQ section sourced from a JSON file containing an array of objects with 'Question' and 'Answer'. https://i.stack.imgur.com/mljpm.png The functionality is such that click ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

React developer server is failing to automatically refresh the code

I've encountered an issue with react-dev-server where changes I make to the code do not reflect on the app itself even after refreshing (not hot-loading). I've tried setting up my own project as well as using Facebook's Create-react-app, whi ...

Trying to utilize RegEx for my project, but feeling stuck on how to solve my problem

^\d{1,12}$|(?=^.{1,15}$)^\d+\.\d{1,2}$ This is the current regular expression I am using. I need to adjust the maximum limit to 100,000,000,000 with an option for two decimal places. Additionally, I would like users to be able to inpu ...