-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (55 loc) · 1.62 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
import React, { Component, PropTypes } from 'react';
import elementResizeEvent from 'element-resize-event';
export class Resize extends Component {
constructor(props) {
super(props);
this.state = {
element: null,
}
this.scaleToAspectRatio = this.scaleToAspectRatio.bind(this);
}
componentDidMount() {
const { onChange = () => {} } = this.props;
const element = this.wrap;
this.setState({ element });
this.scaleToAspectRatio(element);
elementResizeEvent(element, (event) => {
onChange(element, event);
this.scaleToAspectRatio(element);
});
}
aspectRatioMultiplier(ratio) {
if (!ratio) return 0;
if ((ratio.match(/:/g) || []).length !== 1) {
console.log('invalid aspect ratio');
return 0;
}
const ratioValues = ratio.split(':');
return ratioValues[1] / ratioValues[0];
}
scaleToAspectRatio(el) {
const element = el || this.state.element;
const { aspectRatio } = this.props;
const arm = this.aspectRatioMultiplier(aspectRatio);
if (!arm) return;
this.changeHeight(element, element.offsetWidth * this.aspectRatioMultiplier(aspectRatio));
}
changeHeight(element, val) {
element.style.height = `${val}px`;
}
render() {
const { aspectRatio, style = {}, ...rest } = this.props;
return (
<div style={{ width: '100%', ...style }} {...rest} ref={(c) => { this.wrap = c;}}>
{this.props.children}
</div>
);
}
}
Resize.propTypes = {
children: PropTypes.node.isRequired,
aspectRatio: PropTypes.string,
style: PropTypes.object,
onChange: PropTypes.func,
};
export default Resize;