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

After deploying the Next.js application, an error occurred: "Page requested does not match resolved page

After deploying to the server, I am frequently encountering errors like this: Error: Requested and resolved page mismatch: //pipe/31c28e30-fd19-4130-ac0c-32d155841c12/_next/static/jh1CfGVGeGbuBSqLYny_c/_middlewareManifest.js /pipe/31c28e30-fd19-4130-ac0c-3 ...

Switching from real pixels to CSS pixels

The details provided in Mozilla's documentation on elementFromPoint clarify that the coordinates are specified in "CSS pixels" rather than physical pixels. This raises a question about what exactly CSS pixels entail. Many assume that a pixel in CSS is ...

The functionality of the Bootstrap carousel for moving to the next and previous images is malfunctioning, as it only

The carousel on my website is not functioning properly. It only displays the first image and does not slide to the next pictures as it should. Here is the code snippet for the carousel: <body> </nav> <div id="carousel1" class="carousel slid ...

Preventing permission prompts when setting up a fresh React application

Whenever I attempt to create a new react app on my ubuntu os without using sudo, I encounter the following error message: Creating a new React app in /home/bunny/bunny. Installing packages. This might take a couple of minutes. Installing react, react-dom, ...

Tips for positioning two elements side by side in an li element without needing to clear each time

I'm struggling with a stacked list that involves floating an image (icon) alongside text. The constant need to clear after each list item is becoming cumbersome. Anyone have any suggestions for making this more streamlined and tidy? <ul> < ...

I am looking to export multiple 'Pure components'

Currently, I am developing an app using React Native and came across an unusual observation. For some reason, the following code throws an error unless I modify the last sentence to: export default MyButton3; I aim to export more than one pure component ...

Using an if statement within a map function in a React component

I am facing a challenge with using an if statement inside a map function without changing the return value. Here is my code snippet: this.example = this.state.data.map((item) => { return( <div> {if(1 + 1 == 2){ dat ...

Exploring the differences between Material-UI's makeStyles and withStyles when it comes to

One thing I've observed is that the naming convention for classes created with makeStyles and hooks looks like this: https://i.stack.imgur.com/HcDUc.jpg On the other hand, classes produced using withStyles and higher order components (HOC) follow a ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

The input field is failing to capture the final character entered

Is there a way to store all input files in a single object and use the information in a graph? Currently, when I enter the first character, it creates an empty object, so the last character I enter is not captured in the object. Any suggestions on how to ...

Are there any improved methods for optimizing the CSS in my Next.js project?

Currently, I'm immersed in a project using Next.js and styling it with CSS in JS (ReactJSS). Upon inspecting the page source, I noticed that there are over 4000 lines of CSS for a single page, which is not ideal for performance. To provide context, l ...

I'm curious if it's doable to include a tooltip that appears when hovering the mouse cursor over the chosen element in the input for Autocomplete MUI

Can a tooltip be added to an element inside an input when the element is wider than the container and the mouse cursor hovers over it? I attempted to use a Tooltip around a TextField in the renderInput attribute. While this method works, there seems to b ...

The next.js script malfunctions once the router has been altered

My external scripts are not working after the router changes (**When the user clicks on any link**) within _app.js import Script from "next/script"; <Script async type="text/javascript" src= ...

Learn the effective way to style ul elements within @mui/material/Menu using CSS

When the button is clicked, I want to apply the following styles to the ul: &.MuiList-root { padding-top: 0px; padding-bottom: 0px; } View the issue in action on this live sandbox: https://codesandbox.io/s/react-typescript-forked-tyd8n8?fil ...

Loss of styling is observed with jQuery's html() function

Here is the HTML code I am working with: <div class="myList"> <select> <option value="1">Item1</option> <option value="2">Item2</option> </select> </div> Everything looks great in terms of CS ...

Is there a way to make a try-catch block pause and wait for a response before moving

I've been successfully retrieving data from my Firestore database, but I've encountered a major issue that I can't seem to resolve... Whenever I click the "Read Data" button, I have to press it twice in order to see the console log of the d ...

How to verify if an unknown-type variable in TypeScript contains a specific property

When using typescript with relay, the props passed down are of type unknown. Despite my efforts, I am unable to persuade the compiler that it can have some properties without encountering an error: <QueryRenderer environment={environment} query={te ...

What is the best way to incorporate custom data into react-table?

After following the example at while using react-table, everything worked as expected. However, when attempting to use my own data, I encountered an issue where I kept receiving a TypeError stating that 'data is undefined' in useTable. Even thou ...

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...