@carbon/react
Version:
React components for the Carbon Design System
111 lines (107 loc) • 2.93 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* 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 { extends as _extends } from '../../_virtual/_rollupPluginBabelHelpers.js';
import PropTypes from 'prop-types';
import React from 'react';
import cx from 'classnames';
import { usePrefix } from '../../internal/usePrefix.js';
import { noopFn } from '../../internal/noopFn.js';
const Switch = /*#__PURE__*/React.forwardRef(function Switch(props, tabRef) {
const {
children,
className,
disabled,
index,
name,
onClick = noopFn,
onKeyDown = noopFn,
selected = false,
text,
...other
} = props;
const prefix = usePrefix();
const handleClick = e => {
e.preventDefault();
onClick?.({
index,
name,
text
});
};
const handleKeyDown = event => {
// TODO: `which` was deprecated years ago. When can its usage be deleted?
const key = event.key || event.which;
onKeyDown?.({
index,
name,
text,
key
});
};
const classes = cx(className, `${prefix}--content-switcher-btn`, {
[`${prefix}--content-switcher--selected`]: selected
});
const commonProps = {
onClick: handleClick,
onKeyDown: handleKeyDown,
className: classes,
disabled
};
return /*#__PURE__*/React.createElement("button", _extends({
type: "button",
ref: tabRef,
role: "tab",
tabIndex: selected ? 0 : -1,
"aria-selected": selected
}, other, commonProps), /*#__PURE__*/React.createElement("span", {
className: `${prefix}--content-switcher__label`,
title: text
}, text !== undefined ? text : children));
});
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
};
export { Switch as default };