This repository was archived by the owner on May 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
71 lines (55 loc) · 1.77 KB
/
index.js
File metadata and controls
71 lines (55 loc) · 1.77 KB
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
/* eslint no-param-reassign: 0 */
import React, { Component, PropTypes } from 'react';
export default class HeightMatchingGroup extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string,
selector: PropTypes.string,
tagName: PropTypes.string,
}
static defaultProps = {
selector: '.match-height',
tagName: 'span',
}
constructor({ tagName }) {
super();
this.RootTag = `${tagName}`;
}
componentDidMount() {
window.addEventListener('resize', this.matchHeights);
this.preloadAndRun();
}
componentDidUpdate() { this.preloadAndRun(); }
componentWillUnmount() { window.removeEventListener('resize', this.matchHeights); }
getContainerRef = node => { this.container = node; }
getMaxHeight = els => Array.prototype.map.call(els, el => el.scrollHeight).reduce((pre, cur) => Math.max(pre, cur), -Infinity);
loadImages = () => {
const p = new Promise((resolve) => {
const images = this.container.querySelectorAll('img');
let loaded = 0;
const handleImage = () => {
loaded += 1;
if (loaded === images.length) resolve();
};
images.forEach(image => {
image.onload = handleImage;
});
});
return p;
};
preloadAndRun = () => {
this.loadImages().then(this.matchHeights);
setTimeout(this.matchHeights, 0);
}
matchHeights = () => {
const els = this.container.querySelectorAll(this.props.selector);
els.forEach(el => { el.style.height = null; });
const maxHeight = this.getMaxHeight(els);
els.forEach(el => { el.style.height = `${maxHeight}px`; });
}
render = () => (
<this.RootTag className={this.props.className} ref={this.getContainerRef}>
{this.props.children}
</this.RootTag>
)
}