1- import React , { Children , isValidElement , cloneElement , useCallback } from "react"
1+ import React , { Children , isValidElement , cloneElement } from "react"
22import Flex from "@/components/templates/flex"
33import { Button } from "./button"
44
5+ const noop = ( ) => { }
6+
57const getButtonGroupProps = ( itemIndex , itemsLength ) => {
68 const groupFirst = itemIndex == 0
79 const groupLast = itemIndex == itemsLength - 1
@@ -30,20 +32,34 @@ const Content = ({ children }) => {
3032 )
3133}
3234
33- const RadioButtons = ( { items, checked , buttonProps = { } , onChange } ) => {
35+ const RadioButtons = ( { items, value , isMulti , buttonProps = { } , onChange } ) => {
3436 return (
3537 < >
36- { items . map ( ( { label , value , title } , index ) => {
38+ { items . map ( ( item , index ) => {
3739 const buttonGroupProps = getButtonGroupProps ( index , items . length )
38- const isChecked = checked === value || ( Array . isArray ( checked ) && checked . includes ( value ) )
40+ const isSelected =
41+ value === item . value || ( Array . isArray ( value ) && value . includes ( item . value ) )
42+
43+ const onClick = ( ) => {
44+ if ( isMulti ) {
45+ const newValue = Array . isArray ( value )
46+ ? value . includes ( item . value )
47+ ? value . filter ( v => v !== item . value )
48+ : [ ...value , item . value ]
49+ : [ item . value ]
50+ onChange ( newValue )
51+ } else {
52+ onChange ( item . value )
53+ }
54+ }
3955
4056 return (
4157 < Button
42- key = { value }
43- label = { label }
44- onClick = { ( ) => onChange ( value ) }
45- { ...( title ? { title } : { } ) }
46- { ...( ! isChecked ? { flavour : "hollow" } : { } ) }
58+ key = { item . value }
59+ label = { item . label }
60+ onClick = { onClick }
61+ { ...( item . title ? { title : item . title } : { } ) }
62+ { ...( ! isSelected ? { flavour : "hollow" } : { } ) }
4763 { ...buttonGroupProps }
4864 { ...buttonProps }
4965 />
@@ -53,10 +69,24 @@ const RadioButtons = ({ items, checked, buttonProps = {}, onChange }) => {
5369 )
5470}
5571
56- export const ButtonGroup = ( { items, checked, onChange, children, buttonProps, ...props } ) => (
72+ export const ButtonGroup = ( {
73+ items,
74+ value,
75+ isMulti,
76+ onChange = noop ,
77+ children,
78+ buttonProps,
79+ ...props
80+ } ) => (
5781 < Flex alignItems = "center" { ...props } >
5882 { items ?. length ? (
59- < RadioButtons items = { items } checked = { checked } onChange = { onChange } buttonProps = { buttonProps } />
83+ < RadioButtons
84+ items = { items }
85+ value = { value }
86+ isMulti = { isMulti }
87+ onChange = { onChange }
88+ buttonProps = { buttonProps }
89+ />
6090 ) : (
6191 < Content > { children } </ Content >
6292 ) }
0 commit comments