1 | import React, { useCallback, useState } from 'react';
|
2 | import PropTypes from 'prop-types';
|
3 | import classNames from 'classnames';
|
4 | import Button from './Button';
|
5 | import { mapToCssModules } from './utils';
|
6 |
|
7 | const propTypes = {
|
8 | onClick: PropTypes.func,
|
9 | onBlur: PropTypes.func,
|
10 | onFocus: PropTypes.func,
|
11 | defaultValue: PropTypes.bool,
|
12 | className: PropTypes.string,
|
13 | cssModule: PropTypes.object,
|
14 | };
|
15 |
|
16 | function ButtonToggle(props) {
|
17 | const [toggled, setToggled] = useState(props.defaultValue ?? false);
|
18 | const [focus, setFocus] = useState(false);
|
19 |
|
20 | const onBlur = useCallback(
|
21 | (e) => {
|
22 | if (props.onBlur) {
|
23 | props.onBlur(e);
|
24 | }
|
25 | setFocus(false);
|
26 | },
|
27 | [props.onBlur],
|
28 | );
|
29 |
|
30 | const onFocus = useCallback(
|
31 | (e) => {
|
32 | if (props.onFocus) {
|
33 | props.onFocus(e);
|
34 | }
|
35 | setFocus(true);
|
36 | },
|
37 | [props.onFocus],
|
38 | );
|
39 |
|
40 | const onClick = useCallback(
|
41 | (e) => {
|
42 | if (props.onClick) {
|
43 | props.onClick(e);
|
44 | }
|
45 | setToggled(!toggled);
|
46 | },
|
47 | [props.onClick],
|
48 | );
|
49 |
|
50 | const { className, ...attributes } = props;
|
51 |
|
52 | const classes = mapToCssModules(
|
53 | classNames(className, {
|
54 | focus: focus,
|
55 | }),
|
56 | props.cssModule,
|
57 | );
|
58 |
|
59 | return (
|
60 | <Button
|
61 | active={toggled}
|
62 | onBlur={onBlur}
|
63 | onFocus={onFocus}
|
64 | onClick={onClick}
|
65 | className={classes}
|
66 | {...attributes}
|
67 | />
|
68 | );
|
69 | }
|
70 |
|
71 | ButtonToggle.propTypes = propTypes;
|
72 |
|
73 | export default ButtonToggle;
|