forked from ccnokes/react-toggle-display
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ToggleDisplay.jsx
59 lines (49 loc) · 1.1 KB
/
ToggleDisplay.jsx
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
import React from 'react';
import PropTypes from 'prop-types';
ToggleDisplay.propTypes = {
tag: PropTypes.string,
hide: PropTypes.bool,
show: PropTypes.bool,
if: PropTypes.bool
};
ToggleDisplay.defaultProps = {
tag: 'span'
};
const propsToRemove = Object.keys(ToggleDisplay.propTypes);
function isDefined(val) {
return val != null;
}
function shouldHide(props) {
if(isDefined(props.show)) {
return !props.show;
}
else if(isDefined(props.hide)) {
return props.hide;
}
return false;
}
function pickProps(props) {
const newProps = Object.assign({}, props);
propsToRemove.forEach(prop => {
if(prop in newProps) {
delete newProps[prop];
}
});
return newProps;
}
export default function ToggleDisplay(props) {
if(props.if === false) {
return <noscript></noscript>;
// return null // this used to work, now have to manually return <noscript>
}
let style = {};
if(shouldHide(props)) {
style.display = 'none';
}
const Tag = props.tag;
// prevent our props from being leaked down onto the children
const newProps = pickProps(props);
return (
<Tag style={style} {...newProps} />
);
}