Styling animations in React with inline styles

Exploring the world of React inline animation styling, I set out to create a toggle button. The goal was simple: when the user presses the button for the first time, I wanted a pop-up animated card to slide from left to right. On the second press, the card should gracefully close by sliding from right to left. Eager to understand how animations work with inline React styling, I ran into some difficulties. Unfortunately, it seems that React inline styling, transitions, and transforms are not cooperating as expected. Here is the desired animation. You can find my code on code sandbox.

Check out my code snippet:

import { useState } from "react";

export default function App() {
  const [toggle, setToggle] = useState(false);
  return (
    <>
      <button onClick={(): void => setToggle(!toggle)}>toogle button</button>
      {toggle && (
        <div
          style={{
            display: "flex",
            zIndex: 1,
            marginLeft: 170,
            background: "red",
            width: 200,
            height: 300,
            opacity: 1,
            backgroundColor: "tomato",
            transition: "opacity 5s"
          }}
        >
          <p style={{ margin: "0px" }}>animation</p>
        </div>
      )}
    </>
  );
}

Answer №1

Although some may disagree, I believe this approach is worth considering. Here is a potential solution that empowers you to have full control.

 import "./styles.css";

    import { useState } from "react";

    export default function App() {
      const transitions = ["linear", "ease", "ease-in", "ease-out", "ease-in-out"];
      const [opacity, setOpacity] = useState(0);
      const [right, setRight] = useState(40);
      const speed = 0.5;

      return (
        <>
          <button
            onClick={() => {
              setOpacity(opacity ? 0 : 1);
              setRight(prev => prev === 40 ? 20 : 40);
            }}
          >
            toogle button
          </button>
          <div
            style={{
              display: "flex",
              zIndex: 1,
              marginLeft: 170,
              background: "red",
              width: 200,
              height: 300,
              opacity,
              backgroundColor: "tomato",
              transition: `all ${transitions[1]} ${speed}s`,
              transform: `translateX(-${right}%)`
            }}
          >
            <p style={{ margin: "0px" }}>animation</p>
          </div>
          )
        </>
      );
    }

Answer №2

Utilizing inline styles may be an option, but achieving the desired outcome might require CSS or a third-party library to handle animations.

For more information on CSS animations, I suggest checking out: https://www.w3schools.com/css/css3_animations.asp

Another issue to consider:

The content is only displayed when the "toggle" property is true. However, for animations, you need different states in your code to transition between various animation stages.

For example:

  1. <div className="opening">
  2. <div className="opened">
  3. <div className="closing">
  4. <div className="closed">
    (or removed from DOM)

You can then use CSS @keyframes with corresponding CSS selectors for each stage of the animation.

If delving into CSS seems daunting, there are libraries available like this one that can assist:

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

Achieving a consistent fixed width for tbody even when scrollbar is present

thead{ width: calc(100% - 17px); display:block; } tbody{ display:block; overflow-y: auto; height:100px; } http://jsfiddle.net/mkgBx/ Is there a way to adjust the width of the tbody element to match that of the thead element plus the scrollbar? Currently ...

Retrieved data from Axios and used it as the starting value for another state in React Hooks

Can you share any tips on how to set the value fetched from Axios as the initial value of a different state? I'm thinking of using useEffect so that the state updates after rendering. Check out the code snippet below: const [newCode, setNewCode] = ...

swap the positions of two distinct texts

I need to dynamically change the positions of two texts based on the text direction (LTR or RTL) using CSS specifically for an email template. Here is the code snippet I am working with: '<span style="font-weight:bold; text-align: center;">US ...

Denied rendering of design due to incompatible MIME type

Just delved into the world of node / express and decided to test my skills by creating a simple tip calculator app. However, I seem to have hit a roadblock with loading my CSS. The console keeps throwing this error: "Refused to apply style from &apos ...

I have successfully executed Gatsby Graphql queries using GraphiQL, but unfortunately, the same queries do not work on NextJS (where GraphQL queries are configured with Apollo)

Just to verify, both NextJS and Gatsby are connected to a Strapi api that supports GraphQL, with the server running on http://localhost:1337 In addition, I can access the GraphQL playground through http://localhost:1337/graphql However, Gatsby allows me t ...

Styling and Script Files on a JQuery Mobile Website

Is it necessary to include CSS and JS files in every HTML page for a mobile site developed with JQueryMobile? <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://code.jquery.com/jqu ...

What is the process for utilizing npm/yarn installations within a .Net Framework WebAPI project?

In my project, I utilize SCSS and would like to incorporate Bootstrap.scss in order to create a single class that inherits multiple Bootstrap classes. For instance: .myButtonClass { @col-xs-12; @col-sm-6 } This way, I can replace class="col-xs-12 col-sm- ...

Implement various class versions tailored specifically for mobile browsers

While editing a Wordpress theme, I decided to include a content box within Bootstrap's <div class="well">. However, I soon encountered an issue where there was excess space in the content box on desktop view. To address this, I removed the paddi ...

Is it possible to alter the color of the text "midway" within a character on a website?

In some desktop applications, I've noticed a cool feature where the color of text changes as the background evolves. This allows for multiple colors on a single character, which is especially useful when displaying progress bars with percentages insid ...

When Typescript Encounters Compilation Errors, Treat Them as Warnings Instead

After using npx create-react-app my-app --typescript to create my app, I want to set it up in a way that allows me to compile it even when there are typescript errors, so I can address them later. I couldn't find any compilerOptions for this. Is ther ...

How to extract a div from its parent using jQuery

I need to stack two div boxes on top of each other, and my goal is to hide the upper one when it's being hovered over. HTML: <div id="left_middle"> <div id="rfinder_UP"></div> <div id="rfinder_DWN"></div> </div> C ...

Tips for adjusting the placeholder color in Material UI using React JS

Is there a way to customize the background color and flashing color of the Skeleton component in Material UI? I would like to implement custom styling for it, similar to what is shown below: <Skeleton variant="circle" classes={{root:'pla ...

What is the number of steps jQuery animates in?

Exploring my creative side, I decided to create my own custom animate function. Struggling to achieve a seamless animation effect, unlike the smooth transitions produced by jQuery. I'm curious about the formula they utilize to determine the ideal num ...

Is there a discrepancy in the Lodash version number found in the package-lock.json file?

I have upgraded to the latest version of lodash, but in my package-lock.json file it still shows version @4.17.4. Veracode is flagging this as a high risk vulnerability. When I ran npm audit, I received the following message: Invalid: lock file's < ...

Choose only ul elements up to a specific level of depth

ul, ul ul, ul ul ul { list-style: none; margin: 0; padding: 0; } Inquiry: Is there a specific selector that I can utilize to apply styles to every nth level of ul? For instance: ul > ul ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Uh-oh: create-react-app installation has been canceled

As per the guidelines provided in Reactjs documentation: To start a new project, you must have Node version >= 8.10 and npm version >= 5.6 installed on your system. Use the following command to create a project: npx create-react-app my-app My envir ...

What could be causing the sidebar animation to glitch in Internet Explorer when using an *ngFor loop?

I am facing an issue with my animation where it works perfectly in Chrome but not in IE. The desired effect is to slide a panel into view from outside the browser window, and upon clicking the exit button or <div> covering the rest of the page, the p ...

Ways to display a Tooltip automatically without needing to hover using only CSS

I have a tooltip that is set to appear when we hover over the div element, Is there a way to display the tooltip automatically when the page is refreshed without using Javascript? I am looking for a solution in pure CSS only. I attempted to remove displa ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...