You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ToggleButton.js 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // @flow
  2. import React, { useCallback } from 'react';
  3. import { Icon, IconCheck } from '../../../icons';
  4. const mainClass = 'toggle-button';
  5. type Props = {
  6. /**
  7. * Text of the button.
  8. */
  9. children: React$Node,
  10. /**
  11. * If the button is toggled or not.
  12. */
  13. isToggled?: boolean,
  14. /**
  15. * OnClick button handler.
  16. */
  17. onClick: Function
  18. }
  19. /**
  20. * Button used as a toggle.
  21. *
  22. * @returns {ReactElement}
  23. */
  24. function ToggleButton({ children, isToggled, onClick }: Props) {
  25. const className = isToggled ? `${mainClass} ${mainClass}--toggled` : mainClass;
  26. const onKeyPressHandler = useCallback(e => {
  27. if (onClick && (e.key === ' ')) {
  28. e.preventDefault();
  29. onClick();
  30. }
  31. }, [ onClick ]);
  32. return (
  33. <div
  34. aria-checked = { isToggled }
  35. className = { className }
  36. id = 'toggle-button'
  37. onClick = { onClick }
  38. onKeyPress = { onKeyPressHandler }
  39. role = 'switch'
  40. tabIndex = { 0 }>
  41. <div className = 'toggle-button-container'>
  42. <div className = 'toggle-button-icon-container'>
  43. <Icon
  44. className = 'toggle-button-icon'
  45. size = { 10 }
  46. src = { IconCheck } />
  47. </div>
  48. <label htmlFor = 'toggle-button'>{children}</label>
  49. </div>
  50. </div>
  51. );
  52. }
  53. export default ToggleButton;