forked from carbon-design-system/carbon
/
Switch.js
127 lines (106 loc) · 2.66 KB
/
Switch.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
const { prefix } = settings;
const Switch = React.forwardRef(function Switch(props, tabRef) {
const {
children,
className,
disabled,
index,
name,
onClick,
onKeyDown,
selected,
text,
...other
} = props;
const handleClick = (e) => {
e.preventDefault();
onClick({ index, name, text });
};
const handleKeyDown = (event) => {
const key = event.key || event.which;
onKeyDown({ index, name, text, key });
};
const classes = classNames(className, `${prefix}--content-switcher-btn`, {
[`${prefix}--content-switcher--selected`]: selected,
});
const commonProps = {
onClick: handleClick,
onKeyDown: handleKeyDown,
className: classes,
disabled,
};
return (
<button
type="button"
ref={tabRef}
role="tab"
tabIndex={selected ? '0' : '-1'}
aria-selected={selected}
{...other}
{...commonProps}>
<span className={`${prefix}--content-switcher__label`} title={text}>
{text}
{children}
</span>
</button>
);
});
Switch.displayName = 'Switch';
Switch.propTypes = {
/**
* Provide child elements to be rendered inside of the Switch
*/
children: PropTypes.node,
/**
* Specify an optional className to be added to your Switch
*/
className: PropTypes.string,
/**
* Specify whether or not the Switch should be disabled
*/
disabled: PropTypes.bool,
/**
* The index of your Switch in your ContentSwitcher that is used for event handlers.
* Reserved for usage in ContentSwitcher
*/
index: PropTypes.number,
/**
* Provide the name of your Switch that is used for event handlers
*/
name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* A handler that is invoked when a user clicks on the control.
* Reserved for usage in ContentSwitcher
*/
onClick: PropTypes.func,
/**
* A handler that is invoked on the key down event for the control.
* Reserved for usage in ContentSwitcher
*/
onKeyDown: PropTypes.func,
/**
* Whether your Switch is selected. Reserved for usage in ContentSwitcher
*/
selected: PropTypes.bool,
/**
* Provide the contents of your Switch
*/
text: PropTypes.string,
};
Switch.defaultProps = {
selected: false,
text: 'Provide text',
onClick: () => {},
onKeyDown: () => {},
};
export default Switch;