♻️ Simplify the base Checkbox component

This commit is contained in:
Philipp Stracker 2025-01-23 19:40:16 +01:00
parent 5ac017c79e
commit 508c9e85c4
No known key found for this signature in database
2 changed files with 49 additions and 43 deletions

View file

@ -2,48 +2,33 @@ import { CheckboxControl } from '@wordpress/components';
import classNames from 'classnames';
const Checkbox = ( {
currentValue,
label,
value,
checked = null,
disabled = null,
changeCallback,
onChange,
changeCallback, // deprecated.
} ) => {
let isChecked = checked;
if ( null === isChecked ) {
if ( Array.isArray( currentValue ) ) {
isChecked = currentValue.includes( value );
} else {
isChecked = currentValue;
}
}
const className = classNames( { 'ppcp--is-disabled': disabled } );
const onChange = ( newState ) => {
let newValue;
if ( ! Array.isArray( currentValue ) ) {
newValue = newState;
} else if ( newState ) {
newValue = [ ...currentValue, value ];
} else {
newValue = currentValue.filter(
( optionValue ) => optionValue !== value
const handleChange = ( isChecked ) => {
if ( onChange ) {
onChange( value, isChecked );
} else if ( changeCallback ) {
console.warn(
'Deprecated prop, use "onChange" instead of "changeCallback"'
);
changeCallback( value, isChecked );
}
changeCallback( newValue );
};
return (
<CheckboxControl
label={ label }
value={ value }
checked={ isChecked }
checked={ checked }
disabled={ disabled }
onChange={ onChange }
onChange={ handleChange }
className={ className }
/>
);

View file

@ -1,21 +1,42 @@
import { PayPalCheckbox } from './index';
const CheckboxGroup = ( { options, value, onChange } ) => (
<>
{ options.map( ( checkbox ) => (
<PayPalCheckbox
key={ checkbox.value }
label={ checkbox.label }
value={ checkbox.value }
checked={ checkbox.checked }
disabled={ checkbox.disabled }
description={ checkbox.description }
tooltip={ checkbox.tooltip }
currentValue={ value }
changeCallback={ onChange }
/>
) ) }
</>
);
const CheckboxGroup = ( { options, value, onChange } ) => {
const handleChange = ( key, checked ) => {
const getNewValue = () => {
if ( checked ) {
return [ ...value, key ];
}
return value.filter( ( val ) => val !== key );
};
onChange( getNewValue() );
};
return (
<>
{ options.map(
( {
value: itemValue,
label,
checked,
disabled,
description,
tooltip,
} ) => (
<PayPalCheckbox
key={ itemValue }
value={ itemValue }
label={ label }
checked={ checked }
disabled={ disabled }
description={ description }
tooltip={ tooltip }
changeCallback={ handleChange }
/>
)
) }
</>
);
};
export default CheckboxGroup;