-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (50 loc) · 1.3 KB
/
index.js
File metadata and controls
55 lines (50 loc) · 1.3 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
const React = require('react')
const PropTypes = React.PropTypes
/*
* Turns a ratio into a percentage
* Turns `16:9` into `9 / 16` into `56.25%`
* Turns `4:3` into `3 / 4` into `75%`
*/
const ratioToPercent = (ratio) => {
const [w, h] = ratio.split(':').map((num) => Number(num))
return `${(h / w) * 100}%`
}
/*
* Usage:
* <ResponsiveEmbed ratio='4:3'>
* <iframe src='ace youtube video' />
* </ResponsiveEmbed>
*/
const ResponsiveEmbed = ({ratio, style, children, ...props}) => {
const containerStyle = {
position: 'relative',
overflow: 'hidden',
maxWidth: '100%',
height: 0,
paddingBottom: ratioToPercent(ratio),
...style
}
return React.createElement('div', {style: containerStyle, ...props},
React.cloneElement(children, {frameBorder: 0, style: {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
}})
)
}
ResponsiveEmbed.defaultProps = {
ratio: '16:9'
}
ResponsiveEmbed.propTypes = {
children: PropTypes.element.isRequired,
ratio: (props, propName, componentName) => {
if (!/\d+:\d+/.test(props[propName])) {
return new Error(
'Invalid ratio supplied to ResponsiveEmbed. Expected a string like "16:9" or any 2 numbers seperated by a colon'
)
}
}
}
module.exports = ResponsiveEmbed