EN
React - onTransitionEnd fires multiple times
1
answers
0
points
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
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