"Looking to design a custom UI component complete with animations? Here's how to bring your

I attempted to implement the card component, gradient background, and animation but fell short of achieving the desired outcome as seen in the gif. How can I enhance the smoothness of the animation, replicate the exact gradient, and ensure the card stands out like in the image?

[NOTE: Please click on the gif link above if it didn't render correctly]

https://i.sstatic.net/xE3xw.gif

import { useCallback, useEffect, useRef, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import Card from "../Card";
import demoCardData from "../../constants/cardData";

export const ScrollableCardList = ({
  cardData: propCardData,
}: {
  cardData?: Array<any>;
}) => {
  const data = propCardData || demoCardData;
  const containerRef = useRef<HTMLDivElement>(null);
  const [activeIndex, setActiveIndex] = useState(0);

  const handleScroll = useCallback(() => {
    if (!containerRef.current) return;

    const scrollTop = containerRef.current.scrollTop;
    const scrollHeight = containerRef.current.scrollHeight;
    const clientHeight = containerRef.current.clientHeight;

    const scrollRatio = scrollTop / (scrollHeight - clientHeight);
    const newActiveIndex = Math.floor(scrollRatio * data.length);

    setActiveIndex(newActiveIndex);
  }, [data]);

  useEffect(() => {
    if (!containerRef.current) return;

    containerRef.current.addEventListener("scroll", handleScroll);

    return () => {
      if (!containerRef.current) return;
      containerRef.current.removeEventListener("scroll", handleScroll);
    };
  }, [handleScroll]);

  return (
    <div
      ref={containerRef}
      className="flex flex-col items-center h-screen overflow-auto"
      style={{ scrollBehavior: "smooth" }}
    >
      {data.map((card, index) => (
        <Card
          key={uuidv4()}
          imageUrl={card.imageUrl}
          avatarImageUrl={card.avatarImageUrl}
          titleText={card.titleText}
          subTitleText={card.subTitleText}
          isActive={index === activeIndex}
        />
      ))}
    </div>
  );
};
    
    import { Circular, Rectangular, SubTitle, Title } from "./placeholders";
    
    type CardProps = {
      isActive?: boolean;
      cardContainerStyles?: string;
      rectangleContainerStyles?: string;
      circleContainerStyles?: string;
      imageUrl?: string;
      avatarImageUrl?: string;
      titleText?: string;
      subTitleText?: string;
    };
    const Card = ({
      isActive,
      cardContainerStyles,
      rectangleContainerStyles,
      circleContainerStyles,
      imageUrl,
      avatarImageUrl,
      titleText,
      subTitleText,
    }: CardProps) => {
      const activeClass = isActive ? "scale-110" : "";
      // Ensure transition-transform is part of the base class string
      const cardBaseStyles = "transition-transform duration-300 ease-in-out";
      const cardDynamicStyles =
        cardContainerStyles ||
        "w-80 min-h-80 rounded-2xl shadow-4xl p-4 my-4 bg-gradient-to-br from-rose-500 to-rose-400";
      const cardStyles = `${cardBaseStyles} ${activeClass} ${cardDynamicStyles}`;
      const rectangleStyles =
        rectangleContainerStyles ||
        "bg-gradient-to-br from-rose-400 to-[#db7483] w-[100%] h-36 rounded-2xl shadow-2xl";
      const circleStyles =
        circleContainerStyles ||
        "w-12 h-12 rounded-full bg-gradient-to-br from-rose-400 to-rose-300 shadow-md";
    
      return (
        <div className={cardStyles}>
          <Rectangular rectangleStyles={rectangleStyles} imageUrl={imageUrl} />
          <div className="flex items-center mt-5">
            <Circular circleStyles={circleStyles} avatarImageUrl={avatarImageUrl} />
            <div className="flex-grow ml-4">
              <Title titleText={titleText} />
              <SubTitle subTitleText={subTitleText} />
            </div>
          </div>
        </div>
      );
    };
    
    export default Card;

Should I have utilized an animation library for this task? What steps should I take to achieve the exact gradient, popup effect, and animation as depicted in the image? Any guidance or solution provided would be greatly appreciated.

Thank you.

For further implementation, visit the codesandbox link: https://codesandbox.io/p/github/Habi-Thapa/rockandscroll/main?import=true

Answer №1

To achieve the desired effect, you can dynamically adjust the styles of your Card component based on the isActive prop to indicate if it's currently in focus. You can also incorporate a smooth scroll and opacity transition for a seamless transition.

Below is an outline of how you might update both the ScrollableCardList component and the Card component. Note that you may need to refine the types for better code clarity and readability.

For the ScrollableCardList component:

Revise the handleScroll function to identify the card closest to the container center instead of using the scroll ratio. Introduce an additional state to manage card size and opacity values.

Updated ScrollableCardList code:

// ... imports

export const ScrollableCardList = ({
  cardData: propCardData,
}: {
  cardData?: Array<any>;
}) => {
  // code implementation
};

For the Card component:

Adjust the component to accept style as a prop and apply these styles to the main card element.

Here's an example of updating the Card component to accommodate the new styles:

// ... imports

const Card = ({ imageUrl, avatarImageUrl, titleText, subTitleText, style }) => {
  return (
    <div className="card-container" style={{ ...style, transition: 'transform 0.3s, opacity 0.3s' }}>
      {/* Card content */}
    </div>
  );
};

export default Card;

I've created a modified version of your CodeSandbox with these changes implemented for visual reference. You can interact with this updated example here: New Link Here =>

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

Strategizing the organization of a React App with multiple functional areas spread across various ports

Our upcoming web application requires 3 distinct "areas" to be accessible on separate ports, as outlined below: localhost:9001 - Admins localhost:9002 - Customers localhost:9003 - Non-Registered Users The back-end is developed using Hapi/Node and offers ...

Is it possible to apply styling to an element based on the position property of its ancestors using only CSS?

Wondering if it's possible to style an element based on its ancestors' CSS property value. Consider the HTML snippet below: <div><!-- ancestor --> <!-- Any number of descendant levels before reaching the target div --> < ...

Is it possible to save a collection of class instances in Redux?

As I was working my way through a tutorial on Redux, a warning caught my attention: "Redux actions and state should only contain plain JS values like objects, arrays, and primitives. Don't put class instances, functions, or other non-serializable valu ...

Why isn't the show/hide feature in Jquery functioning properly?

I have a div that needs to be displayed after hovering over another element. These elements are not within the same div. The popup info should appear when an icon with the class .option_36_124 is hovered over. $(".option_36_124").hover(function(){ $(& ...

Utilizing a dictionary for comparing with an API response in order to generate an array of unique objects by eliminating duplicates

I currently have a React component that utilizes a dictionary to compare against an API response for address state. The goal is to map only the states that are returned back as options in a dropdown. Below is the mapping function used to create an array o ...

What causes webpack to require 4 seconds for compiling a barebones react / redux project?

I am troubled by the fact that it is still compiling my node_modules even though I have specifically excluded it. How can I investigate and understand what exactly is happening? The output in the console seems like random characters. Is there a way to conf ...

How do you align the back of a Bootstrap flip card to match the front's position precisely?

Can someone assist me with a bootstrap flip card issue I'm facing? I've been trying to create a Bootstrap flip card, but I can't seem to align the back side properly with the front side. Any help would be greatly appreciated! .card-flip&g ...

JavaScript appends a backslash character to a CSS class

I am attempting to populate index.html with the contents from an array using a JavaScript loop. However, I am encountering an issue where a CSS class for picture formatting is displaying some odd characters when rendered in the latest version of Firefox. ...

Incorporating images into CSS using an npm package

My npm package has the following structure: --src --styles -image.png -style.scss In the style.scss file, the image is referenced like this: .test { background-image: url(./image.png); } The issue arises when consuming the package, as th ...

Customize the overlay color using the theme's background color

I want to create an overlay on my webpage that covers all the content. However, I'm facing a challenge because my website allows users to customize the theme colors, and the overlay div does not adopt these color changes automatically. To rectify this ...

Disappearing Data in Chart.js When Window is Resized

I am utilizing the Chart.js library to present a line chart in a div that is enclosed within a <tr>. <tr class="item">...</tr> <tr class="item-details"> ... <div class="col-sm-6 col-xs-12 chart-pane"> <div clas ...

Encountering an issue in Next.js when using getStaticProps: reading 'map' of undefined properties

The Image above shows the error and the code I have attempted.Server Error TypeError: Cannot read properties of undefined (reading 'map') This particular error occurred during the page generation process. Any console logs will appear in the term ...

Guide to Indicating an Icon in Front of an HTML Link and Emphasizing Both with Tap

When using an iOS UIWebview, I am facing the issue of needing to add an icon before standalone links that are within a locally loaded HTML file. In addition to adding the icon, I also need both the icon and link to be highlighted when tapped. The desired ...

Fixed Element Transitioning from Starting Position on Scroll

Check out the JSFiddle example here I'm currently working on a website utilizing Bootstrap 3. I have an image that sticks to the page when scrolling by changing its position to fixed. While this functionality works, the image tends to shift slightly ...

The Bootstrap grid column remains steady and does not fluctuate

Trying to get a grasp on Bootstrap 4, I've set up my page with a three-column layout and defined the following properties for each column: Column 1: col-sm-9 col-md-8 Column 2: col-sm-3 col-md-2 order-sm-first Column 3: col-xs-12 col-md-2 My expecta ...

What steps can I take to ensure that the content remains intact even after the page is

Hey there, I hope you're having a great start to the New Year! Recently, I've been working on creating a calculator using HTML, CSS, and JavaScript. One thing that's been puzzling me is how to make sure that the content in the input field do ...

Is there a way to enable Fancybox to change to the adjacent gallery by simply using the 'up' or 'down' arrow keys?

I am currently working on a layout that consists of a vertical column of thumbnail images, each linked to its own gallery with additional images. When the user clicks on a thumbnail image, Fancybox opens, allowing them to navigate through the images within ...

I am constantly encountering issues with undefined parameters in my express and react website

In my current project, I am working on developing an express + react application that allows users to add, edit, and delete items from a webProjects array. While I have successfully implemented the add function, I am facing some issues with the delete fu ...

React: The Difference Between onClick and OnKeyDown Events

As a React coding beginner, I've been trying to make sense of some interesting behavior in the code I've inherited. The code snippet below controls the closure of a pane/panel in an application that I'm still getting familiar with. However, ...

What is preventing Firefox and IE from displaying images fully in a list item?

I am trying to create a slideshow with two separate sliders using li elements for that purpose. It works perfectly in Chrome and Safari, but I am encountering issues in Firefox and IE. In Firefox, the slideshow works fine in quirks mode but not in standar ...