This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 218
/
package-rates.tsx
78 lines (68 loc) · 1.98 KB
/
package-rates.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* External dependencies
*/
import { useState, useEffect } from '@wordpress/element';
import RadioControl, {
RadioControlOptionLayout,
} from '@woocommerce/base-components/radio-control';
import type { PackageRateOption } from '@woocommerce/type-defs/shipping';
import type { CartShippingPackageShippingRate } from '@woocommerce/type-defs/cart';
/**
* Internal dependencies
*/
import { renderPackageRateOption } from './render-package-rate-option';
interface PackageRates {
onSelectRate: ( selectedRateId: string ) => void;
rates: CartShippingPackageShippingRate[];
renderOption?: (
option: CartShippingPackageShippingRate
) => PackageRateOption;
className?: string;
noResultsMessage: JSX.Element;
selectedRate: CartShippingPackageShippingRate | undefined;
}
const PackageRates = ( {
className = '',
noResultsMessage,
onSelectRate,
rates,
renderOption = renderPackageRateOption,
selectedRate,
}: PackageRates ): JSX.Element => {
const selectedRateId = selectedRate?.rate_id || '';
// Store selected rate ID in local state so shipping rates changes are shown in the UI instantly.
const [ selectedOption, setSelectedOption ] = useState( selectedRateId );
// Update the selected option if cart state changes in the data stores.
useEffect( () => {
if ( selectedRateId ) {
setSelectedOption( selectedRateId );
}
}, [ selectedRateId ] );
if ( rates.length === 0 ) {
return noResultsMessage;
}
if ( rates.length > 1 ) {
return (
<RadioControl
className={ className }
onChange={ ( value: string ) => {
setSelectedOption( value );
onSelectRate( value );
} }
selected={ selectedOption }
options={ rates.map( renderOption ) }
/>
);
}
const { label, secondaryLabel, description, secondaryDescription } =
renderOption( rates[ 0 ] );
return (
<RadioControlOptionLayout
label={ label }
secondaryLabel={ secondaryLabel }
description={ description }
secondaryDescription={ secondaryDescription }
/>
);
};
export default PackageRates;