Animation doesn't apply to child components, but is successful when applied to the parent component

I am working on animating the width of a child component's div. Here is my simple code:

    export const OuterComponent = () => {
      const sidebarCtx = useContext(SidebarContext);
    
      const style =
        "w-[100px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white " +
        (sidebarCtx.isOpen ? " w-[400px] " : "");
    
      const InnerComponent = ({ children }) => {
        return (
          <div className={style}> // applying style directly to this div prevents transition from working
            {children}
            <a>testing</a>
          </div>
        );
      };
    
      return (
        <div className={style}> // applying style here and removing it from InnerComponent allows transition to work normally
          <InnerComponent />
        </div>
      );
    };

The issue, as described in the code comments, lies in the fact that applying style directly to InnerComponent causes the width change to not animate.

Answer №1

When you define InnerComponent inside OuterComponent, it gets reinitiated every time OuterComponent renders, which may be causing issues with your animation.

You can try the following approach:


const InnerComponent = ({ children, classNames }) => {
    return (
        <div className={classNames}>
            {children}
            <a>testing</a>
        </div>
    );
};

export const OuterComponent = () => {
    const sidebarCtx = useContext(SidebarContext);

    const classNames =
        "w-[100px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white " +
        (sidebarCtx.isOpen ? " w-[400px] " : "");

    return (
        <div className={style}>
            <InnerComponent classNames={classNames} />
        </div>
    );
};

Answer №2

By utilizing CSS, you have the ability to easily assign transitions to the container element and then simply hide the overflow of said element. I believe this approach will be successful.

Answer №3

Perhaps this could work for you.

let design = `w-[${sidebarCtx.isOpen ? 400 : 100}px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white`;

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

Following the successful installation of create-react-app, Npm start is refusing to function properly. The error message Enoent with the error number -4058 is

I'm having trouble running my create-react-app on VS code - the npm start command is giving me an error message. Can someone please assist? $ npm start npm ERR! path C:\Users\Jay\Desktop\NucampFolder\3-React\package.json ...

Divergent find function behavior in jQuery when applied to div or tbody

I've encountered an issue while using the jQuery find selector by Id with a div and tbody. Let me simplify my problem for better understanding. HTML <div id='iamdiv'>HELLO</div> <table> <tbody id='iamtbody' ...

Error encountered when attempting to reference multiple Select MenuItems in Material UI

Recently, I've been encountering a perplexing error when attempting to open a multiple Select in React+Next.js using Material UI: Error: Argument appears to not be a ReactComponent. Keys: retry This issue seems to be related to a ref. It occurs with ...

Can you explain the process of gathering texts based on CSS selector?

I wanted to place texts next to the div-class as shown in the following code snippets. <div class="review-contents__text">소재가 좀 저렴해 보이지만 그래도 입으면 휠씬 나아보여요</div> Initially, I wrote a code ...

Having trouble with Typescript in React and Firestore? Wondering why you are receiving the error message "Variable 'l' implicitly has type 'any[]' in some locations where its type cannot be determined.ts"?

For my To Do List project, I am utilizing Next.js/React with Firebase as the backend. The task items consist of name, time required for task completion, and due date fields. My goal is to retrieve the items from the Firebase collection and set them in setD ...

How can I customize the appearance of the container and items in a dropdown <select> menu?

Im using contact form 7 on wordpress, i don't want to use a plugin rather use plain css/js to bring the results if possible. Something like this : https://i.stack.imgur.com/VTWRg.jpg ...

Display previous messages in React JS chat when scrolling upwards

I am currently working on a chat application, as depicted in the image. Once the chat is initiated, it automatically scrolls down to display the most recent messages. My goal is to implement a feature where when a user scrolls up to reach the oldest mess ...

Tips for combining several Launchdarkly initiatives into a unified React application

Discovering how to implement feature flags in multiple Launchdarkly projects from a single provider is explored in the React web docs. The example below illustrates setting up feature flags using different clientSideID values within the same project. impor ...

floating containers aligned side by side in a perfectly positioned parent container

I'm currently working on aligning a set of buttons within a DIV popup that I've created. My goal is to have the buttons positioned next to each other, but I'm having trouble achieving this. I've attempted using 'float: left', ...

Caution: It is not permitted for `<a>` to be nested within another `<a>` tag when working on a Gatsby JS project

I'm currently working with Gatsby JS and react-bootstrap but I'm facing an issue regarding routing. I'm not sure how to properly utilize Gatsby's native routing alongside react-bootstrap, which seems to be using react-router. I attempte ...

Transforming button alignment from vertical to horizontal in Bootstrap based on the screen size of the device

My website features a series of vertically aligned buttons on the sidebar, styled using the following CSS: CSS: .sidebar { position: fixed; left: 20px; top: 5%; width: 120px;} .sidebar .icons { font-size: 30px; margin: 21px; } ...

Setting the timezone for the DateTimeInput component in React-Admin is a crucial step for

My API returns datetime in the format '2021-12-31T16:00:00.000Z' I need to use DateTimeInput and consistently show it in UTC+8 timezone. After the user submits the form, it should convert back to the original format '2021-12-31T16:00:00.000 ...

What is the CSS technique for concealing the content of an ordered list item while retaining the marker?

In our order process, we utilize an ordered list to display the steps in sequence: <ol> <li>Products</li> <li class="active">Customer</li> <li>Payment</li> </ol> On desktop view, it appears a ...

Configuration options for Path Aliases in TypeScript

In my Next.js project, I am utilizing TypeScript and have organized my files as follows: |-- tsconfig.json |-- components/ |---- Footer/ |------ Footer.tsx |------ Footer.module.sass My path aliases are defined as:     "paths": {       ...

Is anyone else experiencing issues with onSuccess and onError not functioning properly in the latest release of React-Query?

Issues are arising in the onSuccess and onError functions. After conducting some research, it appears that these functions have been deprecated in the latest version of React-Query. "use client" import { useRouter, useSearchParams } from 'n ...

Passing JSON data dynamically to create a chart with chartjs

I have also developed this project on codesandbox: https://codesandbox.io/s/bar-graph-9nr8u?file=/src/App.js:2394-3036 I possess JSON data and a Pie graph with labels including car, bikes, motor, and trucks. My goal is to display the total number of users ...

The React Callservice script is failing to fetch the required data from the Node.js script responsible for making the API call

Recently, I decided to create a basic webpage using React.js to display data fetched from an API. Although the project is intended to be straightforward, my lack of recent development experience has led to a perplexing issue that I can't seem to resol ...

No space left around the image's border

Whenever I apply a border to an image, it comes with a margin and the image itself receives white padding. How can I remove the margin from the border? This is how I currently have it: border: 1px solid gray; ...

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...