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:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const normal = {
6
width: '100px',
7
height: '20px',
8
background: 'lightgreen',
9
borderRadius: '20px',
10
transition: '1.5s',
11
outline: 'none',
12
};
13
14
const transformed = {
15
width: '300px',
16
height: '40px',
17
background: 'lightgreen',
18
borderRadius: '20px',
19
transition: '1.5s',
20
outline: 'none',
21
};
22
23
const handleTransitionEnd = (event) => {
24
console.log('transition end');
25
};
26
27
const App = () => {
28
const [buttonStyle, setButtonStyle] = React.useState(false);
29
const handleClick = () => setButtonStyle(!buttonStyle);
30
return (
31
<div onTransitionEnd={handleTransitionEnd}>
32
<button onClick={handleClick} style={buttonStyle ? transformed : normal}>
33
Change size
34
</button>
35
</div>
36
);
37
};
38
39
const root = document.querySelector('#root');
40
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:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const normal = {
6
width: '100px',
7
height: '20px',
8
background: 'lightgreen',
9
borderRadius: '20px',
10
transition: '1.5s',
11
outline: 'none',
12
};
13
14
const transformed = {
15
width: '300px',
16
height: '40px',
17
background: 'lightgreen',
18
borderRadius: '20px',
19
transition: '1.5s',
20
outline: 'none',
21
};
22
23
const handleTransitionEnd = (event) => {
24
if(event.propertyName !== 'width') return;
25
console.log('transition end');
26
};
27
28
const App = () => {
29
const [buttonStyle, setButtonStyle] = React.useState(false);
30
const handleClick = () => setButtonStyle(!buttonStyle);
31
return (
32
<div onTransitionEnd={handleTransitionEnd}>
33
<button onClick={handleClick} style={buttonStyle ? transformed : normal}>
34
Change size
35
</button>
36
</div>
37
);
38
};
39
40
const root = document.querySelector('#root');
41
ReactDOM.render(<App />, root );
0 commentsShow commentsAdd comment