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

Fixing compatibility problems, security risks, alerts, clashes, and disparate releases within React

I am currently working on: Resolving the dependency issues that are surfacing in my React application Gaining a deeper understanding of why these issues are occurring Finding the best approach to address these types of problems properly, without resorting ...

Example of Image Slider using AngularJS

<body ng-app="myApp"> <div ng-controller="slideShowController" class="imageslide" ng-switch='slideshow' ng-animate="'animate'"> <div class="slider-content" ng-switch-when="1"> <img src="../images/ship.png" /> & ...

Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly fil ...

A step-by-step guide on simulating a click event on an element in React with the help of jest and react-testing

My component displays the following {list.options && list.options.length > 0 ? ( <div data-testId="MyAlertText" onClick={onAddText}> Add Text </div> ) : null} When testing, I am executing the following it('Ensure Add Text lin ...

Letters are frolicking in varying sizes and designs

Currently, I am encountering a strange issue with the text on my webpage. Some fonts are displaying with completely different shapes and sizes despite using <meta charset="UTF-8"> to ensure font consistency. Unfortunately, this did not resolve the pr ...

Adjusting the position of the parent div by manipulating the bottom property

Is there a way to toggle the bottom property of a div when clicking its child anchor tag? <div class="nav" :class="{ 'full-width': isFullWidth }"> <a class="toggle-button" @click="toggleNav"><i class="fa fa-angle-down">< ...

How can I utilize CSS to dictate color schemes on an HTML5 canvas element?

Currently, I am working on a checkers project where the first step is to create the initial board. The way we are currently implementing this has raised a philosophical concern. We are using the fillRect function to define the color of the "dark" squares a ...

Simple linking inside a Div container

I'm working on a div that has the following markup: <div class="col-sm-12"> <p class="bg-info">Basic Information</p> </div> Here's how it currently looks: I want to add an 'Add /Edit' link to t ...

Node.js is struggling to locate the package.json file and the project within itself

What should I do if my project is not found on Node.js and npm install is unable to detect my project, resulting in the following error message: Error: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\BLOCKCHAIN EXPERIMENTAL LAB\newflo ...

Describe a Typescript Interface Value as a collection of strings or any input provided as an argument

Uncertain if the question title is accurate - currently developing react components within a library that has specific predefined values for certain properties. However, additional values may need to be added on a per usage basis. So far, this setup is fun ...

Is it unwise to conceal the horizontal scrollbar?

My webpage includes a jquery slideshow using the jquery circle plugin, featuring the "shuffle" option. var slideshow = $('#slider').cycle({ fx: 'shuffle', shuffle: { top: 0, left: 1300}, .... When the images move out ...

Performing height calculations in JavaScript is necessary to recalculate them whenever there is a

A JavaScript function is used to calculate the height of an iframe element and the document height, then determine if the iframe is on or off based on its height and display properties. The issue arises when changing pages— if the height is less than the ...

Error in THREE.js: Failed to retrieve object at http://192.168.8.104:8080/[object%20Object] (Error code: 404) - Module: three.module.js

During my attempt to create a text loader in THREE.js, I encountered an error instead of getting the expected text output. three.module.js:38595 GET http://192.168.8.104:8080/[object%20Object] 404 (Not Found) I made various efforts to resolve this error ...

Can a screenshot of a YouTube video be printed exactly as it appears on a website?

Is there a way to print a page with an embedded YouTube video without it showing up as a blank area? I want the printed version to display the same still shot that appears on the web. If this isn't possible, I will use a noprint stylesheet. Here is ho ...

Calculation error causing incorrect top value display in Chrome [bug alert!]

After dynamically creating an element in jQuery and adding it to the page, I applied a class that sets its position to top:50%. Everything appeared fine at first glance, with the element positioned correctly at 50%. However, when attempting to retrieve the ...

Is it possible to activate a hover effect on an image within a button only when the button itself is being

I'm struggling to figure out how to activate the image hover effect when hovering over a button with an image inside, but not directly over the image itself. Here's what I have so far: <button type="button" class="btn btn-normal"><img s ...

Encountered an issue with useContext in Next.js, displaying the error message: "Unhandled Runtime Error TypeError: Right side of assignment cannot be destructured"

Regarding the middle component used in page.tsx and the error encountered: "use client" import React from 'react' import { CiSearch } from 'react-icons/ci' import { FaPlus } from 'react-icons/fa' // Other import ...

How to initiate a Node script in a React/Express app with the press of a button and stop the script with another button press?

I have crafted a real-time chat bot script using Node.js and developed a simple React/Express application to complement it with basic user controls - one for launching the script and another for terminating it. The chat bot script functions as an ongoing ...

Utilize jQuery to trigger video playback based on the horizontal movement of the mouse

Utilizing this jQuery script to navigate back and forth in a video as the cursor moves along the x-axis. var mouseX; $(document).mousemove( function moveFunc(e) { mouseX = e.clientX; var timV = $("#deko_vid").get(0).duration; var valV = (timV*mouseX/$(do ...

Ensuring that my divs remain stationary despite changes in the size of the browser window

Hey there! I'm new to web design/development and I've been working on a simple website to get the hang of things. I managed to make my webpage look good at full screen, but as soon as I resize the window, everything starts shifting around and it ...