Having some trouble with my React and MUI project - the button animation isn't functioning as expected when clicked

After implementing a Button from MUIv5, I noticed that the full animation only triggers when I hold down the button instead of with a simple click.

Is there a way to fix this so that the animation fully plays with just a single click? Any help is appreciated.

Below is the code snippet:

import Button from "@mui/material/Button";

export default function App() {
  const buttonJSS = {
    ":active": {
      animation: "MoveUpDown 0.3s linear",
      animationFillMode: "forwards"
    },

    "@keyframes MoveUpDown": {
      "0%, 100%": {
        transform: "translateY(0)"
      },
      "50%": {
        transform: "translateY(20px)"
      }
    }
  };

  return (
    <div className="App">
      <Button sx={buttonJSS}>MY BUTTON</Button>
    </div>
  );
}

You can view the code on CodeSandbox: https://codesandbox.io/s/clever-frog-rim6xw?file=/src/App.js

Answer №1

Since the use of :active and the animation duration is set to 0.3 seconds,
the button's activity time is actually less than 0.3 seconds. This results in incomplete styling.

To resolve this issue, you can implement a toggle using className to create the animation:

function App() {
    const { Button } = MaterialUI;

    const [active, setActive] = React.useState(false);

    const buttonJSS = {
        "&.active": {
            animation: "MoveUpDown 0.3s linear",
            animationFillMode: "forwards"
        },

        "@keyframes MoveUpDown": {
            "0%, 100%": {
                transform: "translateY(0)"
            },
            "50%": {
                transform: "translateY(20px)"
            }
        }
    };

    const handleClick = () => {
        setActive(true);
        setTimeout(() => {
            setActive(false);
        }, 300)
    }

    return (
        <div className="App">
            <Button sx={buttonJSS} className={active ? 'active' : ''} onClick={handleClick}>MY BUTTON</Button>
        </div>
    );
  }

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App />);
<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="https://unpkg.com/@mui/material@latest/umd/material-ui.production.min.js"></script>
  </head>
  <body>

    <div id="root"></div>

    <script type="text/babel" src="./script.js"></script>
  </body>
</html>

https://codesandbox.io/s/unruffled-varahamihira-z5tf4u?fontsize=14&hidenavigation=1&theme=dark

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

When modifying a string in React, the edit always somehow ends up at the very tail end

In my ReactJS app, I have a Material-UI input element. Everything is working well except for one issue - when I try to edit the text in the middle of the string, the cursor always jumps to the end of the string after every letter I input. I suspect this m ...

Center the form on the page using Bootstrap

My bootstrap login form is currently appearing at the top of the page, but I want it to be centered. <div class="container"> <div class="row text-center"> <div class="col-sm-6 col-sm-offset-3 well offset4"> <div class=""&g ...

Establishing the default scroll position in tables using React.js

How can I set the initial scroll in ReactJS Material-UI tables? I'm working with a table that has numerous columns and I would like to have specific columns in view automatically without having to scroll, essentially establishing an initial scroll. I ...

revealing a particular field in jQuery during the validation process

Edit: Currently, I am utilizing the jquery validate plugin and have hidden all error messages initially. Upon checking a specific input field, my objective is to unhide the error message if it is invalid without causing error messages to appear in other f ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

Identifying the Operating System and Applying the Appropriate Stylesheet

I am trying to detect the Windows operating system and assign a specific stylesheet for Windows only. Below is the code snippet I have been using: $(function() { if (navigator.appVersion.indexOf("Win")!=-1) { $(document ...

Excessive vertical space is utilized by the vertical images in the CSS grid image gallery

My responsive CSS grid gallery is experiencing issues with vertical images disrupting the layout, as they appear at full size instead of remaining square like the others. How can I fix this problem? Thank you! Below is the code snippet: <div id=" ...

Using AngularJS to Retrieve a Specific DOM Element Using its Unique Identifier

Example Please take a look at this Plunkr example. Requirement I am looking for a way to retrieve an element by its id. The provided code should be capable of applying a CSS class to any existing DOM element within the current view. This functionality ...

Sending information from a rails controller to a react component

Wondering how to pass the example @post = Post.all from the controller to React component props while integrating Rails with React via Webpacker. Is it necessary to do this through an API or is there another way? ...

Transferring an MSAL token to the backend with the help of Axios

I encountered an issue while attempting to send the user ID, which was previously decoded from a JWT token along with user input data. The problem arises when I try to send the data and receive an exception in the backend indicating that the request array ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

React throwing a typescript error while attempting to update state based on the previous state

Hello there! I'm fairly new to working with TypeScript and I've encountered an issue with a piece of state in a child component. I'm trying to modify it based on the previous value, but every time I call the setState function, I get a type e ...

disable the button border on native-base

I'm attempting to enclose an icon within a button, like so: <Button style={styles.radioButton} onPress={() => { console.log('hdjwk'); }}> <Icon ...

Can someone clarify the actual version of webpack.js being used in my Ruby on Rails application with --webpacker=react configuration?

My tech stack includes Ruby 2.7.1, yarn 1.22.5, Rails 6.0.4.4, and node v16.13.1 I recently followed a tutorial on integrating React into my Rails project from this link The tutorial led me to install webpacker 4.3.0 automatically in my Gemfile.lock file ...

How to implement SVG in React with the image source as a parameter?

I've been working on a React component in NextJS that displays an image inside a hexagon. The issue I'm facing is that when I try to use multiple instances of this component with different images in the HexagonWall, all hexagons end up displaying ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

The icon on my page is not displaying, and the responsive menu is also not appearing

After tweaking the @media {} settings, I noticed that the icon displays properly when reduced, but disappears completely when fully covered with {}. Additionally, my responsive menu is not visible as expected. `@import url('https://fonts.googleap ...

Is there a way I can decrease the width of the input field on the left side?

body { background: white; font-family: 'Ubuntu', sans-serif; } .cas { display: inline-block; border: 2px solid #0C8346; background: #0C8346; font-weight: 300; font-size: 20px; padding: 5px; width: 200px; text-align: center; ...

implementing a scroll-up animation using Material UI

Check out this link https://react.dev/community#stack-overflow where you'll find https://i.stack.imgur.com/DSXnM.png As you scroll back up, you will come across https://i.stack.imgur.com/LoOj6.png Is there a ready-made Material UI component that ca ...

Subnav sticks when scrolling down but becomes unresponsive on resizing

My webpage has a main header that sticks to the top of the window and a subnav fixed at the bottom. The hero image adjusts its height based on the window minus the header and subnav heights. When scrolling past the subnav, it sticks just below the main nav ...