Languages

React - onTransitionEnd fires multiple times

0 points
Asked by:
Dirask Community
5610

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:
Dirask Community
5610

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
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