-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
81 lines (77 loc) · 2.34 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import React, { Component } from "react";
import PropTypes from "prop-types";
export default class CrossfadeImage extends Component {
constructor(props) {
super(props);
this.state = {
topSrc: props.src,
bottomOpacity: 0,
bottomSrc: props.src
};
}
componentWillReceiveProps(newProps) {
const oldSrc = this.state.topSrc;
const newSrc = newProps.src;
if (newSrc !== oldSrc) {
// Reset the component everytime we receive new prop, to
// cancel out any animation that's still going on
this.setState({ bottomSrc: false, topSrc: false }, () =>
this.setState(
// Opacity less than 1 takes precendence in stacking order
{ bottomSrc: oldSrc, topSrc: newSrc, bottomOpacity: 0.99 },
() => {
// One of the few times setTimeout does wonders, this is for
// getting fade out transition without css keyframe
if (!this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(
() => this.setState({ bottomOpacity: 0 }),
20
);
}
)
);
}
}
render() {
const { containerClass, duration, timingFunction, delay, style, alt } = this.props;
const { topSrc, bottomOpacity, bottomSrc } = this.state;
return (
<div className={containerClass} style={{ ...defaultStyle, ...{ position: "relative" } }}>
{topSrc &&
<img
style={{ ...defaultStyle, ...style, ...{ position: "absolute" } }}
src={topSrc}
alt={alt}
/>}
{bottomSrc &&
<img
style={{
...defaultStyle,
...style,
...{
opacity: bottomOpacity,
transition: `opacity ${duration / 1000}s ${timingFunction} ${delay / 1000}s`
}
}}
src={bottomSrc}
/>}
</div>
);
}
}
const defaultStyle = { maxWidth: "100%", maxHeight: "100%" };
CrossfadeImage.propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string,
duration: PropTypes.number,
timingFunction: PropTypes.string,
delay: PropTypes.number,
style: PropTypes.object,
containerClass: PropTypes.string,
};
CrossfadeImage.defaultProps = {
duration: 500,
timingFunction: "ease",
delay: 0,
containerClass: "CrossfadeImage",
};