SpicyyRiice
SpicyyRiice

Reputation: 156

React and MUI - My clicking button animation isn't working like I wanted

I have this Button from MUIv5 and I would like to fully animate it once it's pressed.

The problem is I have to hold the button to make the full animation and not just one simple click

How can I fix it? Thanks in advance.

Here's the code.

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>
  );
}

The link of the codesandbox is here: https://codesandbox.io/s/clever-frog-rim6xw?file=/src/App.js

Upvotes: 2

Views: 1519

Answers (1)

Amr Eraky
Amr Eraky

Reputation: 1781

Because you're using :active, and the time of animation is 0.3 second,
But Button activity time is less than 0.3 second. So the styling is not complete.

You can use className toggle to make this 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>

Edit geocoding-demo (forked)

Upvotes: 2

Related Questions