Languages

React - onTransitionEnd fires multiple times

0 points
Asked by:
Mikolaj
489

Does anyone know why my handleTransitionEnd function is being executed twice after my component changes? How to fix it?

My code:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const normal = {
  width: '100px',
  height: '20px',
  background: 'lightgreen',
  borderRadius: '20px',
  transition: '1.5s',
  outline: 'none',
};

const transformed = {
  width: '300px',
  height: '40px',
  background: 'lightgreen',
  borderRadius: '20px',
  transition: '1.5s',
  outline: 'none',
};

const handleTransitionEnd = (event) => {
  console.log('transition end');
};

const App = () => {
  const [buttonStyle, setButtonStyle] = React.useState(false);
  const handleClick = () => setButtonStyle(!buttonStyle);
  return (
    <div onTransitionEnd={handleTransitionEnd}>
      <button onClick={handleClick} style={buttonStyle ? transformed : normal}>
        Change size
      </button>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
1 answer
0 points
Answered by:
Mikolaj
489

I found the solution:

  • pass event to the handleTransitionEnd event handling function,
  • insert a simple if statement inside the function so it doesn't take into account one of the properties.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const normal = {
  width: '100px',
  height: '20px',
  background: 'lightgreen',
  borderRadius: '20px',
  transition: '1.5s',
  outline: 'none',
};

const transformed = {
  width: '300px',
  height: '40px',
  background: 'lightgreen',
  borderRadius: '20px',
  transition: '1.5s',
  outline: 'none',
};

const handleTransitionEnd = (event) => {
  if(event.propertyName !== 'width') return;
  console.log('transition end');
};

const App = () => {
  const [buttonStyle, setButtonStyle] = React.useState(false);
  const handleClick = () => setButtonStyle(!buttonStyle);
  return (
    <div onTransitionEnd={handleTransitionEnd}>
      <button onClick={handleClick} style={buttonStyle ? transformed : normal}>
        Change size
      </button>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join